鉴于这 2 行中的值,为什么我的查询返回 0 行以及如何重写查询以使其正常工作?

meta_id post_id meta_key   meta_value
   1422      73 wpcf-milk      22
   1423      73 wpcf-mw        -7

SQL查询:
   SELECT * FROM wp_postmeta
    WHERE post_id = 73
    AND ( meta_key = 'wpcf-mw' AND meta_value BETWEEN -8 AND 200 )
    AND ( meta_key = 'wpcf-milk' AND meta_value BETWEEN 20 AND 200 )

最佳答案

基本上有两种方法可以做到这一点。一种大致如下:

SELECT post_id
     , MAX(CASE WHEN meta_key = 'wpcf-milk' THEN meta_value END) wpcf_milk
     , MAX(CASE WHEN meta_key = 'wpcf-mw' THEN meta_value END) wpcf_mw
  FROM wp_postmeta
 GROUP
    BY post_id
HAVING wpcf_milk BETWEEN 20 AND 200
   AND wpcf_mw BETWEEN -8 AND 200;

另一种方法涉及 OUTER JOINs,速度稍快,但打字有点乏味——所以我会把它留给其他人。

关于Mysql查询返回0个结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30087862/

10-11 15:58