【问题标题】:Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated columnORDER BY 子句的表达式 #1 不在 GROUP BY 子句中,并且包含非聚合列
【发布时间】:2018-06-12 19:50:05
【问题描述】:

我正在尝试通过 meta_value 订购 wp_query

我使用以下参数

array(
  'post_type'      =>'event',
  'posts_per_page' => -1,
  'meta_query'     => array(
  'dates_query' => array(
          'key' => 'dates',
          'value' => date(time()),
          'compare' => '>='
          )
       ),
  'orderby'        => 'dates_query',
  'order'          => 'ASC',
  'paged'          => 1
);

这是由 wp_query 生成的请求

SELECT wp_posts.* FROM wp_posts 
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) 
WHERE 1=1 AND ( ( wp_postmeta.meta_key = 'dates' 
         AND wp_postmeta.meta_value >= '1514960717' ) ) 
         AND wp_posts.post_type = 'event' 
         AND (wp_posts.post_status = 'publish' 
         OR wp_posts.post_status = 'completed' 
         OR wp_posts.post_status = 'acf-disabled') 
         GROUP BY wp_posts.ID 
         ORDER BY CAST(wp_postmeta.meta_value AS CHAR) ASC

不幸的是,结果是错误的,当尝试手动执行查询时,我得到以下错误:

Expression #1 of ORDER BY clause is not in GROUP BY clause and contains non-aggregated column

我知道有一个选项可以禁用“only_full_group_by”,但我想知道在这种情况下这是否是最佳做法

谢谢

【问题讨论】:

  • 你为什么首先与GROUP BY 聚合?您从未在查询中实际使用它。没有看到任何相反的东西,我建议你摆脱GROUP BY

标签: mysql wordpress


【解决方案1】:

不确定您为什么使用 data_query 但您应该尝试直接在键值比较上使用 meta_query。让我知道它是否有效。

array(
    'post_type'     => 'event',
    'posts_per_page'=> -1,
    'paged'          => 1,
    'meta_key'      => 'dates',
    'orderby'       => 'meta_value',
    'order'         => 'ASC',
    'meta_query'    => array(
            array(
                'key'       => 'dates',
                'value'     =>  date(time()), //<-- Cross check if your date has same format.
                'compare'   => '>=',
                'type'      => 'DATE'
            )       
    )               
);

【讨论】:

    【解决方案2】:

    我无法对 wp_query 发表评论,但作为参考,这里有一个有效查询的示例(虽然我无法想象为什么要将整数像字符串一样排序):

    SELECT DISTINCT p.* 
      FROM wp_posts p
      JOIN wp_postmeta m
        ON p.ID = m.post_id
     WHERE m.meta_key = 'dates'
       AND m.meta_value >= '1514960717'
       AND p.post_type = 'event'
       AND p.post_status IN('publish','completed','acf-disabled')
     ORDER 
        BY CAST(m.meta_value AS CHAR) ASC;
    

    【讨论】:

      猜你喜欢
      • 2017-06-22
      • 1970-01-01
      • 2016-12-12
      • 2017-07-29
      • 2016-04-27
      • 1970-01-01
      • 2017-05-04
      • 2019-01-22
      • 1970-01-01
      相关资源
      最近更新 更多