0

我的示例表:

汽车选项

| ID | CAR_ID |    DESCRIPTION |
|----|--------|----------------|
|  1 |      5 | tinted windows |
|  2 |      5 |  power windows |
|  3 |      6 |  power windows |
|  4 |      7 | tinted windows |

如何编写一个 sql 语句,该语句接受输入“有色窗户”和“电动车窗”并返回第 1 行和第 2 行(它们在 car_id 列中共享一个公共值)?

4

2 回答 2

1

使用 获取与输入匹配的所有行WHERE,然后每个输入GROUP BY的 car_idHAVING至少有一行。您可以使用下面的查询来做到这一点。

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)
于 2013-09-13T05:31:58.667 回答
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

输出:

| 身份证 | CAR_ID | 说明 |
|----|--------|----------------|
| 1 | 5 | 有色窗户| 高分辨率照片| CLIPARTO
| 2 | 5 | 电动车窗| 高分辨率照片| CLIPARTO

这是SQLFiddle演示

于 2013-09-13T05:45:09.080 回答