IN子句选择所有变量

时间:2012-03-13 19:39:52

标签: mysql

当我运行此程序时:

SELECT * FROM photo 
LEFT JOIN photo_selectedTags
ON photo.COUNTER = photo_selectedTags.PHOTO_COUNTER
WHERE photo_selectedTags.TAGS_COUNTER IN (6,192)

它检索TAGS_COUNTER = 6 OR 192

的行

如何从“照片”中检索行,其中TAGS_COUNTER = 6 AND 192?

更正:IN for ALL

3 个答案:

答案 0 :(得分:1)

基本理念是:

SELECT PHOTO_COUNTER
FROM photo_selectedTags 
WHERE TAGS_COUNTER in (6, 192)
group by PHOTO_COUNTER
having count(distinct TAGS_COUNTER) = 2 --2 matches # of items in IN clause

然后,您可以执行此操作以获取其余列:

SELECT *
from PHOTO_COUNTER 
LEFT JOIN photo_selectedTags
ON photo.COUNTER = photo_selectedTags.PHOTO_COUNTER
where photo.COUNTER in (
    SELECT PHOTO_COUNTER
    FROM photo_selectedTags 
    WHERE TAGS_COUNTER in (6,192)
    group by PHOTO_COUNTER
    having count(distinct TAGS_COUNTER) = 2 --2 matches # of items in IN clause
) a

答案 1 :(得分:0)

修改

现在我明白了你想要的和DB结构,试试这个:

SELECT * FROM photo 
LEFT JOIN photo_selectedTags
ON photo.COUNTER = photo_selectedTags.PHOTO_COUNTER
WHERE photo_selectedTags.TAGS_COUNTER = 6 AND photo_id IN
(SELECT photo_id FROM photoSELECT * FROM photo 
LEFT JOIN photo_selectedTags
ON photo.COUNTER = photo_selectedTags.PHOTO_COUNTER
WHERE photo_selectedTags.TAGS_COUNTER = 192)

我不知道photo_id是否是您桌子的实际字段,但尝试将其调整为您的结构

显然在第一个SELECT中不插入PHOTO_COUNTER,因为我将始终使用相同的值并且没有多大意义。

答案 2 :(得分:0)

我建议使用2个连接

SELECT *
FROM photo

JOIN photo_selectedTags as photo_selectedTags6 -- this join restricts to 'photo.COUNTER' whic have TAGS_COUNTER = 6
ON photo.COUNTER = photo_selectedTags6.PHOTO_COUNTER
AND photo_selectedTags6.TAGS_COUNTER = 6

JOIN photo_selectedTags as photo_selectedTags192 -- this join restricts to 'photo.COUNTER' whic have TAGS_COUNTER = 192
ON photo.COUNTER = photo_selectedTags192.PHOTO_COUNTER
AND photo_selectedTags192.TAGS_COUNTER = 192



也可以使用分析功能(如果您的数据库支持)来实现它

-- This one works on teradata. Something similar should work on oracle. Don't know about others
SELECT *
FROM photo 
LEFT JOIN photo_selectedTags
ON photo.COUNTER = photo_selectedTags.PHOTO_COUNTER
QUALIFY max(case when photo_selectedTags.TAGS_COUNTER = 6 then 1 end) over (partition by photo.COUNTER) = 1
AND max(case when photo_selectedTags.TAGS_COUNTER = 192 then 1 end) over (partition by photo.COUNTER) = 1

如果列表中有很多值(除了192,6之外),那么这可能是解决方案

SELECT *
FROM photo
JOIN
(
    SELECT PHOTO_COUNTER, count(distinct TAGS_COUNTER) cnt
    FROM photo_selectedTags
    WHERE TAGS_COUNTER in (192,6)
    HAVING cnt = 2 -- adjust this according to the number of different values
) as pht
ON photo.COUNTER = pht.PHOTO_COUNTER

在子查询中只剩下PHOTO_COUNTER,它们都有(192和6),然后加入