SQL左侧连接的同一列上的2个值的SQL

时间:2014-08-31 04:11:55

标签: sql database

我需要帮助:

我有一张名为 phonograms phonogram_instruments 过滤器的表格:

在phonograms表上,我有很多数据可以在我的应用上获取。一个录音制品有许多phonogram_instruments,每个phonogram_instrument都属于一个滤镜。

我需要获取所有有phonogram_instrument.filter_id = 25的phonogram和phonogram_instrument.filter_id = 30

我有一个查询可以正常使用一个值:

SELECT * FROM "phonograms" 
LEFT OUTER JOIN "phonogram_instruments" "phonogram_instruments_phonograms" 
   ON "phonogram_instruments_phonograms"."phonogram_id" = "phonograms"."id" 
WHERE 
   (phonogram_instruments_phonograms.filter_id = 29)

但是如果我放了另一个值,它就没有了:

 SELECT * FROM "phonograms" 
LEFT OUTER JOIN "phonogram_instruments" "phonogram_instruments_phonograms"
   ON "phonogram_instruments_phonograms"."phonogram_id" = "phonograms"."id" 
WHERE 
   (phonogram_instruments_phonograms.filter_id = 29)
   AND (phonogram_instruments_phonograms.filter_id = 25)
你可以帮帮我吗? :)

2 个答案:

答案 0 :(得分:1)

单个filter_id行无法同时具有29和25的值

因此,您应该使用OR而不是AND

SELECT * FROM "phonograms" 
LEFT OUTER JOIN "phonogram_instruments" "phonogram_instruments_phonograms" 
ON "phonogram_instruments_phonograms"."phonogram_id" = "phonograms"."id" 
WHERE 
 phonogram_instruments_phonograms.filter_id = 29
 OR phonogram_instruments_phonograms.filter_id = 25

如果你的where语句包含更多过滤器,请将filter_id过滤器语句放在两个括号

之间
SELECT * FROM "phonograms" 
LEFT OUTER JOIN "phonogram_instruments" "phonogram_instruments_phonograms" 
ON "phonogram_instruments_phonograms"."phonogram_id" = "phonograms"."id" 
WHERE 
 (
   phonogram_instruments_phonograms.filter_id = 29
   OR phonogram_instruments_phonograms.filter_id = 25
 )
 AND ... other filters

答案 1 :(得分:0)

我的第一个想法是使用这样的INTERSECT复合运算符:

SELECT * FROM "phonograms" 
LEFT OUTER JOIN "phonogram_instruments" "phonogram_instruments_phonograms" 
   ON "phonogram_instruments_phonograms"."phonogram_id" = "phonograms"."id" 
WHERE 
   phonogram_instruments_phonograms.filter_id = 29
INTERSECT
SELECT * FROM "phonograms" 
LEFT OUTER JOIN "phonogram_instruments" "phonogram_instruments_phonograms" 
   ON "phonogram_instruments_phonograms"."phonogram_id" = "phonograms"."id" 
WHERE 
   phonogram_instruments_phonograms.filter_id = 25

如果您需要与任意数量的filter_id相交(例如,找到phonogram_instrument.filter_id为29,25和37的所有录音制品),它并不是特别漂亮且不能很好地缩放。在这种情况下,我可能会建议一个有趣的替代方案(顺便提一下,它也适用于两个值):

SELECT * FROM "phonograms", count(phonograms.id) as 'num_ids'
LEFT OUTER JOIN "phonogram_instruments" "phonogram_instruments_phonograms" 
   ON "phonogram_instruments_phonograms"."phonogram_id" = "phonograms"."id" 
WHERE 
   phonogram_instruments_phonograms.filter_id IN (29, 25)
GROUP BY
   phonograms.id
HAVING
   num_ids = 2

如果您有2个以上的filter_id,请展开WHERE子句中的括号列表,并相应地更改HAVING子句中的数值。