Reputation: 35
I thought I had this query built correctly to skip results that are NULL yet the NULL rows still show:
SELECT post_id,
MAX(CASE WHEN meta_key = '_payment_meta'
THEN meta_value
END) as 'DeliveryDate'
FROM postmeta
WHERE 'DeliveryDate' IS NOT NULL
GROUP BY post_id
What is being missed where it is still showing the NULL results?
Upvotes: 1
Views: 51
Reputation: 42632
'
are used to quote string literals, to quote column name you must use backtick char. WHERE 'DeliveryDate' IS NOT NULL
checks does the string literal 'DeliveryDate'
is not null which is always TRUE - i.e. this condition do nothing.So:
SELECT post_id,
MAX(CASE WHEN meta_key = '_payment_meta'
THEN meta_value
END) as `DeliveryDate`
FROM postmeta
GROUP BY post_id
HAVING `DeliveryDate` IS NOT NULL
From the other side - you need post_id
with meta_key = '_payment_meta'
- so you may filter rows before grouping and do simple
SELECT post_id,
MAX(meta_value) as `DeliveryDate`
FROM postmeta
WHERE meta_key = '_payment_meta'
GROUP BY post_id
This query will do the same.
If (post_id, meta_key, meta_value)
is defined as UNIQUE (which is logical if the table stores only actual data, not values history) then the query may be simplified to
SELECT post_id,
meta_value as `DeliveryDate`
FROM postmeta
WHERE meta_key = '_payment_meta'
Upvotes: 2
Reputation: 104
'DeliveryDate' in the WHERE clause is being interpreted as a string literal ... and as such IS NOT NULL
Upvotes: 1