MySQL:从一列中选择包含值的多行
的 car_id,并且在值列中用户输入值为“200”:
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。
我想找到具有“FORD”和“SILVER”的汽车 为此创建 SQL 查询的方法是什么?
I'd like to find the car_id's of the cars that have 'FORD' AND 'SILVER' AND the user input value of '200' in the value column:
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 |
+----+--------+----------+-----------+
Which in this case should return only one car_id: car_id = 2.
What would be the way to go to create the SQL query for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您拥有的是一个属性表。当您想要一次测试多个属性时,您需要将表连接到自身:
在属性表中存在代理
id
是有问题的。它似乎什么也没做;每个属性都不是自己的实体。除非其他元素需要id
,否则我会删除它并使car_id, name
主键(复合主键)。What you have is a properties table. When you want to test multiple properties at once you need to join the table to itself:
Having the surrogate
id
present in a properties table is questionable. It doesn't seem to be doing anything; each property isn't an entity of its own. Unless theid
is required by some other element, I'd get rid of it and makecar_id, name
the primary key (a composite primary key).我假设每辆车都需要有可变的参数,否则你不会采用这样的设置。如果 MAKE、CARLINE、COLOR 和 TOPSPEED 各有自己的列,那就容易多了。
但是,使用您提供的表,您需要使用子查询。 http://dev.mysql.com/doc/refman/5.0/en /subqueries.html
查询应如下所示(未经测试):
I assume that every car needs to have variable parameters, otherwise you wouldn't have gone with a setup like this. It would be much easier if MAKE, CARLINE, COLOR, and TOPSPEED each had their own column.
Using the table you've provided, however, you need to use subqueries. http://dev.mysql.com/doc/refman/5.0/en/subqueries.html
The query should look something like this (untested):