我的示例表:
CAR OPTIONS
| ID | CAR_ID | DESCRIPTION |
|----|--------|----------------|
| 1 | 5 | tinted windows |
| 2 | 5 | power windows |
| 3 | 6 | power windows |
| 4 | 7 | tinted windows |
如何编写一个sql语句,它接受输入'tinted windows'和'power windows'并返回第1行和第2行(它们在car_id列中共享一个公共值)?
答案 0 :(得分:1)
使用WHERE
获取与输入匹配的所有行,然后为每个输入获取GROUP BY
car_id HAVING
至少一行。您可以使用下面的查询来执行此操作。
SELECT car_id
FROM CarOptions
WHERE (description = "tinted windows" OR
description = "power windows")
GROUP BY car_id
HAVING SUM(description = "tinted windows") > 0 AND
SUM(description = "power windows") > 0
请参阅demo
要获得整行,
SELECT *
FROM CarOptions
WHERE car_id IN (
SELECT car_id
FROM CarOptions
WHERE (description = "tinted windows" OR
description = "power windows")
GROUP BY car_id
HAVING SUM(description = "tinted windows") > 0 AND
SUM(description = "power windows") > 0)
答案 1 :(得分:1)
在这种特殊情况下,你可以做到
SELECT *
FROM caroptions o JOIN
(
SELECT car_id
FROM caroptions
WHERE description IN('tinted windows', 'power windows')
GROUP BY car_id
HAVING COUNT(DISTINCT description) = 2
) q
ON o.car_id = q.car_id
输出:
| ID | CAR_ID | DESCRIPTION | |----|--------|----------------| | 1 | 5 | tinted windows | | 2 | 5 | power windows |
这是 SQLFiddle 演示