![](/img/trans.png)
[英]Selecting all rows with only one value in column with another common value
[英]Selecting rows that share a common value in one column, but were selected by other values
我的示例表:
汽車選擇
| 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列中共享一個公共值)?
獲取與使用該輸入的所有行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
見演示
要獲得整行,你可以做到,
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)
在這種特殊情況下你可以做到
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演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.