在MySQL上,给出下表(image_tags):
image_id | tag_id
-----------------
1 | 100
1 | 20
2 | 100
3 | 20
我想选择tag_id = 100 AND tag_id = 20的行,在这种情况下我想要的结果是:
image_id
--------
1
我试过,但我找不到在纯SQL中执行此操作的正确方法。谢谢!
答案 0 :(得分:3)
假设(image_id
,tag_id
)对是唯一的:
SELECT image_id
FROM image_tags
WHERE tag_id IN ('20', '100')
GROUP BY image_id
HAVING count(*) = 2
答案 1 :(得分:1)
试试这个:
SELECT image_id FROM MyTable
WHERE tag_id IN (100,20)
GROUP BY image_id
HAVING COUNT(*) = 2
如果您想选择每一行,请尝试以下一行:
SELECT * FROM MyTable
WHERE image_id IN
(
SELECT image_id FROM MyTable
WHERE tag_id IN (100,20)
GROUP BY image_id
HAVING COUNT(*) = 2
)
答案 2 :(得分:1)
简单的JOIN查询
SELECT a.image
FROM image_tags a
INNER JOIN image_tags b ON a.image_id = b.image_id AND b.tag_id = 20
WHERE a.tag_id = 100
或使用计数,但如果图像有重复标签,则应对
SELECT DISTINCT image_id
FROM image_tags
WHERE tag_id in ('20', '100')
GROUP BY image_id
HAVING count(DISTINCT tag_id) = 2
答案 3 :(得分:0)
你所做的是对的,你也可以尝试这个
从image_tags中选择*其中tag_id in('100','20',....)
答案 4 :(得分:0)
SELECT Image_ID FROM
(SELECT Image_ID FROM tab
WHERE Tag_ID = 100) tag100
JOIN
(SELECT Image_Id FROM tab
WHERE TagID = 20) tag20
我认为这就是你在寻找的东西 - 你想要那些TagID等于20且TagID等于100的记录,对吗?
答案 5 :(得分:0)
select image_id
from image_tags
where image_id IN (
select image_id
from image_tags
where tag_id = 100)
AND tag_id = 20
答案 6 :(得分:0)
您可以使用
select image_id from test
where image_id IN (select image_id from test
where tag_id = '100') AND tag_id = '20'
检查Demo