对不起,伙计们,我用了一个不同的例子,而不是使用来自w3school的w3school表,而是更新了我的问题,并给出了真实的情况。
我使用wordpress,我想过滤掉所有有多个类别的帖子。
`SELECT DISTINCT p.id,p.post_title,p.post_content,t.name,tax.taxonomy from
wp_posts as p
LEFT JOIN wp_term_relationships rel ON rel.object_id = p.ID
LEFT JOIN wp_term_taxonomy tax ON tax.term_taxonomy_id =
rel.term_taxonomy_id
LEFT JOIN wp_terms t ON t.term_id = tax.term_id
WHERE 1=1
AND p.post_status = 'publish'
AND p.post_title LIKE '%lorem%'
OR p.post_content LIKE '%lorem%' `我想使用原始sql,因为我知道条件会更长。
以下是我得到的https://d.pr/free/i/mrNHXk
但当我加上这个
`AND t.name = 'CGN'
AND t.name = 'Harmony'`我没有结果,我期待着这个https://d.pr/free/i/0NER1F
使用
AND t.name IN ('CGN','Harmony')将无法工作,因为如果我在以下条件下添加了“cfw”,则结果必须同时具有“cgn”和“cfw”。
AND t.name IN ('CGN','Harmony','cfw')结果职位应该有这三个类别
发布于 2019-01-31 02:51:34
不要直接与分类法表连接,而是使用子查询和存在谓词来检查post中是否存在标记Harmony和CGN。
select p.id, p.post_title, p.post_content,
(select GROUP_CONCAT(t.name) from wp_term_relationships rel
inner join wp_term_taxonomy tax ON tax.term_taxonomy_id = rel.term_taxonomy_id
inner join wp_terms t ON t.term_id = tax.term_id
where rel.object_id = p.ID) as terms
from wp_posts as p
where
p.post_status = 'publish'
and (p.post_title LIKE '%lorem%' OR p.post_content LIKE '%lorem%' )
and exists (select * from wp_term_relationships rel
inner join wp_term_taxonomy tax ON tax.term_taxonomy_id = rel.term_taxonomy_id
inner join wp_terms t ON t.term_id = tax.term_id
where rel.object_id = p.ID and t.name = 'Harmony')
and exists (select * from wp_term_relationships rel
inner join wp_term_taxonomy tax ON tax.term_taxonomy_id = rel.term_taxonomy_id
inner join wp_terms t ON t.term_id = tax.term_id
where rel.object_id = p.ID and t.name = 'CGN')发布于 2019-01-31 02:19:34
您将不会获得该查询的任何结果。原因在于,国家价值不可能同时是“德国”和“美国”(以逻辑/命题的方式)。
尝试:
SELECT * FROM Customers WHERE Country in ('Germany','USA')
其他可能性:
SELECT * FROM Customers WHERE Country like '%Germany%' or like '%USA%'
发布于 2019-01-31 02:30:07
如前所述,德国、和美国都不应该存在。你似乎在寻找:
SELECT * FROM Customers
WHERE Country IN ('Germany', 'USA');使用带有list的IN子句将返回国家包含德国或美国的customer表中的所有行。
https://stackoverflow.com/questions/54452356
复制相似问题