MySQL:选择包含一列值的多行

时间:2010-09-29 00:33:59

标签: mysql select

我想在价值栏中找到'FORD'和'SILVER'以及用户输入值'200'的汽车的car_id:

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   |
    +----+--------+----------+-----------+

在这种情况下,应该只返回一个car_id:car_id = 2.

为此创建SQL查询的方法是什么?

2 个答案:

答案 0 :(得分:5)

您拥有的是属性表。如果要一次测试多个属性,则需要将表连接到自身:

SELECT c0.car_id
FROM table_cars AS c0
JOIN table_cars AS c1 ON c1.car_id=c0.car_id
JOIN table_cars AS c2 ON c2.car_id=c1.car_id
WHERE c0.name='MAKE' AND c0.value='FORD'
AND c1.name='COLOR' AND c1.value='SILVER'
AND c2.name='TOPSPEED' AND c2.value='200KM/H'

让属性表中存在代理id是值得怀疑的。它似乎没有做任何事情;每个财产都不是自己的实体。除非某些其他元素需要id,否则我会删除它并使car_id, name成为主键(复合主键)。

答案 1 :(得分:1)

我认为每辆车都需要有可变参数,否则你不会选择这样的设置。如果MAKE,CARLINE,COLOR和TOPSPEED都有自己的专栏会更容易。

但是,使用您提供的表,您需要使用子查询。 http://dev.mysql.com/doc/refman/5.0/en/subqueries.html

查询应该看起来像这样(未经测试):

SELECT * FROM table_cars WHERE id IN (SELECT * FROM table_cars WHERE name="MAKE" AND value="FORD") AND id IN (SELECT * FROM table_cars WHERE name="COLOR" AND value="SILVER") AND id IN (SELECT * FROM table_cars WHERE name="TOPSPEED" AND value="200KM/H")