如何缩小我的代码搜索结果?
例如,
root_tags
tag_id tag_name
1 A
2 B
root_mm_tagged_pages
tag_id pg_id
1 10
1 20
2 10
我希望获得包含pg_id 10
我尝试使用下面的查询,但它返回空:
SELECT *
FROM root_tags
LEFT JOIN root_mm_tagged_pages
ON root_mm_tagged_pages.tag_id = root_tags.tag_id
WHERE root_tags.tag_name = 'A'
AND root_tags.tag_name = 'B'
ORDER BY root_mm_tagged_pages.created_on DESC
注意:我得到A
到$_REQUEST
的值,因此它始终是动态的。但B
始终是固定的。
有什么想法吗?
感谢。
答案 0 :(得分:1)
WHERE root_tags.tag_name = 'A'
AND root_tags.tag_name = 'B'
您的意思是OR root_tags.tag_name = 'B'
吗?
编辑 Nvm,但是怎么样:
WHERE root_tags.tag_name IN ('A', 'B')
答案 1 :(得分:1)
SELECT * FROM(SELECT * 来自root_mm_tagged_pages
将root_tags加入为At ON At.tag_id = root_mm_tagged_pages.tag_id)AS Aat JOIN
(SELECT * 来自root_mm_tagged_pages
将root_tags加入为Bt ON Bt.tag_id = root_mm_tagged_pages.tag_id)AS Bbt on Aat.pg_id = Bbt.pg_id WHERE Aat.tag_name ='A'和Bbt.tag_name ='B'
ORDER BY Aat.created_on DESC
我认为这应该是慢的,也许等待另一个解决方案:)
答案 2 :(得分:0)
在我问的类似问题中,“nick rulez”给出了一个非常令人满意的答案: MySQL query equivalent of "AND", whereas "IN" is "OR"?
select x
from table
where y in (2,3)
group by x
having count(distinct(y)) = 2
在你的情况下,它将是:
select pg_id
from root_mm_tagged_pages
where tag_id in ('A', 'B')
group by pg_id
having count(distinct(tag_id)) >= 2
这将返回至少包含标记'A'
和'B'
的任何结果。
但是,如果你想要一个更“一般情况”的搜索算法,我认为它可以这样改进:
select pg_id
from root_mm_tagged_pages
where tag_id in (/* any amount of tags */)
group by pg_id
having count(distinct(tag_id)) > 0
order by count(distinct(tag_id)) desc
哪个会返回至少包含1个匹配标记的每个结果,但首先会返回匹配标记最多的结果。
答案 3 :(得分:0)
我的回答源自汤米的提示,
SELECT * FROM
( SELECT root_mm_tagged_pages.tag_id as Atag_id, root_mm_tagged_pages.pg_id as Apg_id, At.tag_name as Atag_name FROM root_mm_tagged_pages
LEFT JOIN root_tags as At ON At.tag_id = root_mm_tagged_pages.tag_id ) AS Aat JOIN
( SELECT root_mm_tagged_pages.tag_id as Btag_id, root_mm_tagged_pages.pg_id as Bpg_id, Bt.tag_name as Btag_name FROM root_mm_tagged_pages
LEFT JOIN root_tags as Bt ON Bt.tag_id = root_mm_tagged_pages.tag_id ) AS Bbt on Aat.Apg_id = Bbt.Bpg_id WHERE Aat.Atag_name = 'A' AND Bbt.Btag_name = 'B'
感谢