选择包含一列值的多行

时间:2014-11-17 08:54:57

标签: mysql sql database select

实际上我的问题与MySQL: Select multiple rows containing values from one column几乎相同,我想找到有MAKE =' FORD'的汽车的car_id。 AND COLOR =' SILVER',所以在这种情况下,它将返回car_id 1和2.

PS:可以同时有多个标准,例如我可以通过MAKE + CARLINE + COLOR,MAKE + CARLINE等进行搜索。

table_cars

+----+--------+----------+-----------+
| id | car_id | name     | value     |
+----+--------+----------+-----------+
| 1  | 1      | MAKE     | FORD      |
| 2  | 1      | CARLINE  | FIESTA    |
| 3  | 1      | COLOR    | SILVER    |
| 4  | 1      | TOPSPEED | 210KM/H   |
| 5  | 2      | MAKE     | FORD      |
| 6  | 2      | CARLINE  | FOCUS     |
| 7  | 2      | COLOR    | SILVER    |
| 8  | 2      | TOPSPEED | 200KM/H   |
| 9  | 3      | MAKE     | HOLDEN    |
| 10 | 3      | CARLINE  | ASTRA     |
| 11 | 3      | COLOR    | WHITE     |
| 12 | 3      | TOPSPEED | 212KM/H   |
+----+--------+----------+-----------+

谢谢!

2 个答案:

答案 0 :(得分:0)

尝试自我加入,如下所示:

SELECT distinct car_id
FROM mytable mt1 INNER JOIN mytable mt2
ON   mt1.car_id = mt2.car_id
WHERE mt1.name = 'MAKE'
AND   mt1.value = 'FORD'
AND   mt2.name = 'COLOR'
AND   mt2.value = 'SILVER'

答案 1 :(得分:0)

select car_id
from your_table
group by car_id
having sum(name = 'MAKE' and value = 'FORD') > 0
and sum(name = 'COLOR' and value = 'SILVER') > 0