在 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 中执行此操作的正确方法。谢谢!
假设 ( image_id
, tag_id
) 对是唯一的:
SELECT image_id
FROM image_tags
WHERE tag_id IN ('20', '100')
GROUP BY image_id
HAVING count(*) = 2
试试这个:
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
)
简单的 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
你做的是对的你也可以试试这个
select * from image_tags where tag_id in ('100','20',....)
SELECT Image_ID FROM
(SELECT Image_ID FROM tab
WHERE Tag_ID = 100) tag100
JOIN
(SELECT Image_Id FROM tab
WHERE TagID = 20) tag20
我认为这就是您要寻找的内容-您想要那些同时具有等于 20 的 TagID 和等于 100 的 TagID 的记录,对吗?
select image_id
from image_tags
where image_id IN (
select image_id
from image_tags
where tag_id = 100)
AND tag_id = 20
您可以使用
select image_id from test
where image_id IN (select image_id from test
where tag_id = '100') AND tag_id = '20'
检查演示