目前,我有2个表格,其中包含以下数据:
[CAR]
Honda
Ford
Mazda
[FEATURE]
CD player
Sunroof
Leather
在另一张表中,我存储了他们的关系。
[CAR_FEATURE]
Honda | CD Player
Mazda | CD Player
Mazda | Sunroof
Mazda | Leather
我的问题是......我需要选择 [CAR] ,其中包含我想要的所有 [FEATURE] - 全部或全部。
例如,如果我正在寻找带有 CD播放器,天窗和皮革的汽车,那么它将输出马自达。
如果我正在寻找带有 CD播放器的汽车,那么它只能输出本田。
如果我正在寻找一辆带有天窗的汽车,那么它不会输出任何东西,因为我正在搜索全部或全部。
对于这种特殊情况,我如何在SQL中编写查询语句?
答案 0 :(得分:0)
这样可行:
SELECT CAR
FROM CAR_FEATURE
WHERE FEATURE IN ('CD Player', 'Sunroof', 'Leather')
GROUP BY CAR
HAVING COUNT(*) = 3
只需根据功能调整HAVING
子句,您可以传入CSV功能列表并创建一个具有所有功能的TABLE变量表,以便查询可以是这样的:
DECLARE @LIST_OF_FEATURES TABLE(FEATURE VARCHAR(50))
--INSERT INTO THE @LIST_OF_FEATURES USING THE FORXML
SELECT CAR
FROM CAR_FEATURE
WHERE FEATURE IN (SELECT FEATURE FROM @LIST_OF_FEATURES)
GROUP BY CAR
HAVING COUNT(*) = (SELECT COUNT(*) FROM @LIST_OF_FEATURES)
答案 1 :(得分:0)
我不知道确切的表结构,因此我将使用字段名称进行即兴创作。我希望从背景中可以清楚地看出:
SELECT c.*
FROM CAR c
JOIN CAR_FEATURE cf ON (c.id = cf.car_id)
JOIN FEATURE f ON (f.id = cf.feature_id)
LEFT JOIN FEATURE f2 ON (f2.id = cf.feature_id
AND f2.id NOT IN (<list of feature ids>))
WHERE f.id IN (<same list of features ids as above>)
AND f2.id IS NULL
这会使具有您想要的功能但没有任何其他功能的汽车。
具体例子。假设您的功能ID是名称(不是一个好主意,但对示例有好处),那么您会写:
SELECT c.*
FROM CAR c
JOIN CAR_FEATURE cf ON (c.id = cf.car_id)
JOIN FEATURE f ON (f.id = cf.feature_id)
LEFT JOIN FEATURE f2 ON (f2.id = cf.feature_id
AND f2.id NOT IN ('CD Player','Sunroof'))
WHERE f.id IN ('CD Player','Sunroof')
AND f2.id IS NULL
希望这有帮助!
答案 2 :(得分:0)
T McKeown查询的这种变化将为您提供一辆完全匹配所有功能的汽车,而不是更多或更少:
SELECT CAR
FROM CAR_FEATURE
GROUP BY CAR
HAVING SUM(CASE WHEN FEATURE IN ('CD Player', 'Sunroof', 'Leather')
THEN 1
ELSE -1
END) = 3