假设name
您要搜索的字段在wp_terms
表中,则有两个主要选项。
第一个只是查找具有第一类的实体,然后使用另一个连接来查找也具有第二类的实体。这涉及在两个不同的连接中使用同一个表,因此使用别名并避免使用using
关键字。
select * from wp_links l
inner join wp_term_relationships r on l.link_id = r.object_id
inner join wp_term_taxonomy t on r.term_taxonomy_id = t.term_taxonomy_id
inner join wp_terms c1 on t.term_id = c1.term_id
inner join wp_terms c2 on t.term_id = c2.term_id
where taxonomy = "link_category"
and c1.name = 'stuff'
and c2.name = 'other_stuff'
替代方案的可扩展性远不止两个类别,而是涉及一个子查询......
select
l.*
from
(
select l.id from wp_links l
inner join wp_term_relationships r on l.link_id = r.object_id
inner join wp_term_taxonomy t on r.term_taxonomy_id = t.term_taxonomy_id
inner join wp_terms c on t.term_id = c.term_id
where taxonomy = "link_category"
and c.name IN ('stuff', 'other_stuff')
group by l.id
having count(distinct c.name) = 2
)
subquery
inner join wp_links l ON subquery.id = l.id
内部查询查找所有具有一个类别或另一个类别的内容,但是 having 子句只允许那些在我们的列表中具有两个类别的内容。(换句话说,它们都是。) [它还假设wp_links
表作为id
列用作唯一标识符。]