ORDER BY子句的表达式#1不在GROUP BY子句中,并且包含非聚合列

时间:2018-01-03 06:28:35

标签: mysql wordpress

我试图通过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”,但我想知道这是否是这种情况下的最佳做法

由于

2 个答案:

答案 0 :(得分:0)

不确定为什么使用了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'
            )       
    )               
);

答案 1 :(得分:0)

我无法对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;