0

我可以从 WordPress 数据库中获取特定类别的链接(为了清楚起见,我在 SQL 部分添加了换行符):

$category1 = 'stuff';
$category2 = 'other_stuff';

$q = 'select * from wp_links l
    inner join wp_term_relationships r on l.link_id = r.object_id
    inner join wp_term_taxonomy using (term_taxonomy_id)
    inner join wp_terms using (term_id)
    where taxonomy = "link_category"
    and name = '.$category1;

$results = $wpdb->get_results($q);

我将如何检索同时属于和的链接(我的意思是两个类别 ,而不是任何一个类别)?$category1$category2

4

2 回答 2

0

你试过OR吗?

   $q = 'select * from (select * from wp_links l
        inner join wp_term_relationships r on l.link_id = r.object_id
        inner join wp_term_taxonomy using (term_taxonomy_id)
        inner join wp_terms using (term_id)
        where taxonomy = "link_category"
        and name = '.$category1.') as t1 join (select * from wp_links l
        inner join wp_term_relationships r on l.link_id = r.object_id
        inner join wp_term_taxonomy using (term_taxonomy_id)
        inner join wp_terms using (term_id)
        where taxonomy = "link_category"
        and name = '.$category2 .') as t2
        on t1.term_id=t2.term_id;

我不认为这是最好的解决方案,但你没有给我更多关于你的结构的细节,表你有什么

于 2012-07-02T17:26:18.823 回答
0

假设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列用作唯一标识符。]

于 2012-07-02T17:52:34.017 回答