WHERE clause great than zero still showing zero when using CASE functions

泪湿孤枕 提交于 2021-02-05 11:19:26

问题


I am trying the WHERE clause to filter out other data I dont want.

SELECT `post_id`,
       MAX(CASE WHEN `meta_key` = 'vlaue_1' THEN `meta_value` ELSE NULL END) as 'Customer',
       MAX(CASE WHEN `meta_key` = 'value_2' THEN `meta_value` ELSE NULL  END) as 'DeliveryDate',
        MAX(CASE WHEN `meta_key` = 'value_3' THEN `meta_value` ELSE NULL  END) as 'DeliveryTime',
         MAX(CASE WHEN `meta_key` = 'vlaue_4' THEN `meta_value` ELSE NULL  END) as 'DeliveryType'
FROM wp_postmeta 
WHERE 'Customer' > 0
GROUP BY `post_id`  
ORDER BY `wp_postmeta`.`post_id` ASC

The above is returning the error 'Truncated incorrect DOUBLE value'. Yes I have looked this up a number of places including stackoverflow and understand its meaning except not in this instance.

OK so I thought I wouldnt use 'customer' at all. No problem. I will tell it to search for when the 'Customer'is not null using WHERE 'Customer' IS NOT NULL. That gives me this image where it displays everything null AND the records I am seeking. pic of db when not null

What am I missing here?


回答1:


Your WHERE logic belongs in a HAVING clause:

SELECT
    post_id,
    MAX(CASE WHEN meta_key = 'vlaue_1' THEN meta_value END) AS Customer,
    MAX(CASE WHEN meta_key = 'value_2' THEN meta_value END) AS DeliveryDate,
    MAX(CASE WHEN meta_key = 'value_3' THEN meta_value END) AS DeliveryTime,
    MAX(CASE WHEN meta_key = 'value_4' THEN meta_value END) AS DeliveryType
FROM wp_postmeta 
GROUP BY post_id
HAVING Customer > 0
ORDER BY post_id;

Note that your current WHERE clause might technically be valid MySQL:

WHERE 'Customer' > 0

However, this checks whether the string literal 'Customer' is greater than the value 0. It does not actually check the value of the customer case expression, which is not even available until after group by happens.



来源:https://stackoverflow.com/questions/63432930/where-clause-great-than-zero-still-showing-zero-when-using-case-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!