我需要从表中获得结果,其中分组ID存在于其中field1 = a且field2 IS NOT NULL的行中,但不是其中field1 = b且field2为IS的行。只是语法错误,不知道如何结合这些标准......
这就是我要做的事情:
SELECT a.post_title AS title, a.id,
MAX(CASE WHEN b.meta_key = 'endorser' THEN b.meta_value END) endorser,
MAX(CASE WHEN b.meta_key = 'trail' THEN b.meta_value END) trail,
MAX(CASE WHEN b.meta_key = 'townarea' THEN b.meta_value END) townarea,
MAX(CASE WHEN b.meta_key = 'state' THEN b.meta_value END) state,
MAX(CASE WHEN b.meta_key = 'start-date' THEN b.meta_value END) startdate,
MAX(CASE WHEN b.meta_key = 'description' THEN b.meta_value END) description,
MAX(CASE WHEN b.meta_key = 'organizer-name' THEN b.meta_value END) organizer,
MAX(CASE WHEN b.meta_key = 'info-email' THEN b.meta_value END) infoemail
FROM wp_posts a LEFT JOIN wp_postmeta b ON a.id = b.post_id
WHERE b.post_id IN
(SELECT Post_id FROM wp_postmeta
WHERE (meta_key = 'endorser' AND meta_value IS NOT NULL)
AND (meta_key = 'trail' AND meta_value IS NULL)) group by b.post_id
表格看起来像这样:
meta_id | post_id | meta_key | meta_value
---------|-------------|------------|------------
1 | 53 | endorser | joe
2 | 54 | trail | trail name
所以我会得到包含post_id 53但不是54
的行我很累,所以我可能会错过一些简单的东西,比如一个简单的OUTER JOIN?
答案 0 :(得分:1)
您可以使用b.meta_key IN ('endorser','trail')
删除子查询,并在where子句中使用CASE
表示您的null为空且不为空标准
SELECT a.post_title AS title, a.id,
(SELECT MAX(meta_value) FROM wp_postmeta WHERE meta_key = 'endorser' AND post_id =a.id) endorser,
(SELECT MAX(meta_value) FROM wp_postmeta WHERE meta_key = 'trail' AND post_id =a.id) trail,
(SELECT MAX(meta_value) FROM wp_postmeta WHERE meta_key = 'townarea' AND post_id =a.id) townarea,
(SELECT MAX(meta_value) FROM wp_postmeta WHERE meta_key = 'state' AND post_id =a.id) state,
(SELECT MAX(meta_value) FROM wp_postmeta WHERE meta_key = 'start-date' AND post_id =a.id) startdate,
(SELECT MAX(meta_value) FROM wp_postmeta WHERE meta_key = 'description' AND post_id =a.id) description,
(SELECT MAX(meta_value) FROM wp_postmeta WHERE meta_key = 'organizer-name' AND post_id =a.id) organizer,
(SELECT MAX(meta_value) FROM wp_postmeta WHERE meta_key = 'info-email' AND post_id =a.id) infoemail
FROM wp_posts a
LEFT JOIN wp_postmeta b ON a.id = b.post_id
WHERE b.meta_key IN ('endorser','trail')
AND (
CASE
WHEN b.meta_key = 'endorser'
THEN b.meta_value IS NOT NULL
WHEN b.meta_key = 'trail'
THEN b.meta_value IS NULL
END
)
HAVING trail =''
答案 1 :(得分:0)
不要使用LEFT JOIN,请使用INNER JOIN
FROM wp_posts a INNER JOIN wp_postmeta b ON a.id = b.post_id