Mysql 选择在一列中共享公共值但被其他值选中的行

Mysql 选择在一列中共享公共值但被其他值选中的行,mysql,sql,Mysql,Sql,我的示例表: 汽车选择 | ID | CAR_ID | DESCRIPTION | |----|--------|----------------| | 1 | 5 | tinted windows | | 2 | 5 | power windows | | 3 | 6 | power windows | | 4 | 7 | tinted windows | 如何编写一条sql语句,获取输入“着色窗”和“电动窗”,并返回第1行和第2行(

我的示例表:

汽车选择

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

如何编写一条sql语句,获取输入“着色窗”和“电动窗”,并返回第1行和第2行(它们在car\u id列中共享一个公共值)?

使用
WHERE
获取与输入匹配的所有行,然后
对每个输入至少有一行的car\u id
进行分组。您可以使用下面的查询来执行此操作

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 | |ID |汽车ID |描述| |----|--------|----------------| |1 | 5 |有色窗户| |2 | 5 |电动车窗|
这里是演示

@user2775071它有帮助吗?