对不起,标题有点令人费解!
我到处都有一点点搜索,但我不确定我是否正确地写出了正确的结果,或者我想做什么甚至是可能的......
基本上我想返回表中与另一个值匹配的所有值。 我有桌子:
Table "Cars" Table "Models"
Car_ID Car Car_ID Model_ID Model
------------------- ----------------------------
1 Ford 1 14 Mustang
2 Fiat 1 21 Focus
3 Toyota 1 87 Escort
2 78 500
2 45 Punto
3 66 Aygo
如果我只搜索一个模型名称(例如Escort),我想要这些结果:
Car Model_ID Model
------------------------
Ford 14 Mustang
Ford 21 Focus
Ford 87 Escort
因此,搜索汽车模型将返回所有相同品牌的模型。
任何人都有任何想法?
答案 0 :(得分:1)
这是你要找的吗?
SELECT c.Car, m.Model_ID, m.Model
FROM Models m
INNER JOIN Cars c ON c.Car_ID = M.Car_ID
WHERE m.Car_ID = (SELECT Car_ID FROM Models WHERE Model = 'Escort');
答案 1 :(得分:1)
您可以使用此查询。如果有多个具有相同名称的模型,则此查询将返回所提供的模型名称的所有相应品牌中的所有模型。
SELECT c.Car, m.Model_ID, m.Model
FROM Models AS m_search
INNER JOIN Cars AS c
ON m_search.Car_ID = c.Car_ID
INNER JOIN Models AS m
ON c.Car_ID = m.Car_ID
WHERE m_search.Model = ?
PostgreSQL上的示例(因为MySQL不支持WITH
):
chris=$ WITH Cars (Car_ID, Car) AS (VALUES
(1, 'Ford'),
(2, 'Fiat'),
(3, 'Toyota')
), Models (Car_ID, Model_ID, Model) AS (VALUES
(1, 14, 'Mustang'),
(1, 21, 'Focus'),
(1, 87, 'Escort'),
(2, 78, '500'),
(2, 45, 'Punto'),
(3, 66, 'Agyo')
)
SELECT c.Car, m.Model_ID, m.Model
FROM Models AS m_search
INNER JOIN Cars AS c
ON m_search.Car_ID = c.Car_ID
INNER JOIN Models AS m
ON c.Car_ID = m.Car_ID
WHERE m_search.Model = 'Escort';
car | model_id | model
------+----------+---------
Ford | 14 | Mustang
Ford | 21 | Focus
Ford | 87 | Escort
(3 rows)
答案 2 :(得分:1)
试试这个:
select c.Car, m.Model_ID, m.Model from Cars c, Models m where c.Car_ID=m.Car_ID
and Car_ID in (select Car_ID from Models where Model='Escort')
答案 3 :(得分:0)
您可以使用子查询来检索模型的Car_ID
:
select *
from Models m
join Cars c
on c.Car_ID = m.Car_ID
where m.Car_ID =
(
select Car_ID
from Models
where Model = 'Mustang'
)
答案 4 :(得分:0)
根据您正在查看的表的大小,可以更有效地在子查询中获取信息,而不是使用“in”或连接。
select ( select car from cars where car_id = m.car_id ), model_id, model
from models m
where car_id = ( select car_id from from models where model = 'Escort' )