gpt4 book ai didi

php - 我可以排除复杂查询中满足条件的行吗? (组合 WHERE + 多重 AND)

转载 作者:行者123 更新时间:2023-11-29 13:09:30 24 4
gpt4 key购买 nike

我需要从表中获取结果,其中分组 ID 存在于 field1 = a 且 field2 IS NOT NULL 的行中,但不存在 field1 = b 且 field2 IS NOT NULL 的行中。只是出现语法错误,不太知道如何组合这些标准...

这就是我正在尝试做的事情:

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?

这是 fiddle :http://sqlfiddle.com/#!2/ee5420/1

最佳答案

您可以使用 b.meta_key IN ('endorser','trail') 来摆脱子查询,并且在 where 子句中您可以使用 CASE 作为您的 is为 null 且不为 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 =''

Fiddle Demo

关于php - 我可以排除复杂查询中满足条件的行吗? (组合 WHERE + 多重 AND),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22292920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com