抱歉,我使用的是一个不同的示例,而不是使用w3school的COuntry表,我更新了问题并提供了实际情况。
我正在使用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”和“ harmony”
AND t.name IN ('CGN','Harmony','cfw')
结果发布应具有这3个类别
答案 0 :(得分:2)
您将不会获得该查询的任何结果。原因是“国家/地区”值不能同时(以逻辑/命题的方式)同时为“德国”和“美国”。
尝试:
SELECT * FROM Customers WHERE Country in ('Germany','USA')
其他可能性:
SELECT * FROM Customers WHERE Country like '%Germany%' or like '%USA%'
答案 1 :(得分:2)
不要直接与分类表连接,而是使用子查询和exists谓词来检查该帖子是否存在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')
答案 2 :(得分:1)
如上所述,国家/地区既是德国又是的情况不应该存在。看来您正在寻找:
$result = [];
foreach (array_unique($rows, SORT_REGULAR) as $row) {
$result[$row['DayofWeek']][] = $row;
}
将IN子句与列表一起使用将返回客户表中该国家/地区包含 德国或美国的所有行。
https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_in2