我在MySQL数据库中有这些表:
买家
ID|SELLER
----------------
0 |Paul
1 |Jean
2 |David
3 |Jack
4 |John
5 |Fred
6 |Peter
PARIS
ID|CAR
---------
0 |Toyota
1 |BMW
2 |Honda
LONDON
ID|CAR
---------
3 |Ford
4 |BMW
5 |Honda
6 |Honda
我使用followinq查询:
SELECT b.id, b.seller, p.car
FROM buyers b
JOIN paris p
ON b.id = p.id
UNION ALL
SELECT b.id, b.seller, l.car
FROM buyers b
JOIN london l
ON g.id = l.id;
获得以下结果:
ID|SELLER |CAR
----------------
0 |Paul |Toyota
1 |Jean |BMW
2 |David |Honda
3 |Jack |Ford
4 |John |BMW
5 |Fred |Honda
6 |Peter |Honda
我想检索“本田”为“CAR”的行,我试图用“Where car ='Honda'”附加查询,但没有成功..
感谢您的帮助
答案 0 :(得分:1)
仅添加WHERE car = 'Honda'
是不明确的。应该检查哪个车栏?
实现此目的的最简单方法是将现有查询包装在另一个select语句中,以便查询应用于结果表,即
SELECT * FROM
(
SELECT b.id, b.seller, p.car
FROM buyers b
JOIN paris p
ON b.id = p.id
UNION ALL
SELECT b.id, b.seller, l.car
FROM buyers b
JOIN london l
ON g.id = l.id;
)
WHERE car = 'Honda'
答案 1 :(得分:1)
添加
WHERE car = 'Honda';
对您的查询的仅引用第二个查询,即UNION ALL
之后的查询。
所以:
SELECT b.id, b.seller, p.car FROM buyers b JOIN paris p ON b.id = p.id
WHERE p.car = 'Honda'
UNION ALL
SELECT b.id, b.seller, l.car FROM buyers b JOIN london l ON b.id = l.id
WHERE p.car = 'Honda'
;
或
SELECT id, seller, car
FROM
(
SELECT b.id, b.seller, p.car FROM buyers b JOIN paris p ON b.id = p.id
UNION ALL
SELECT b.id, b.seller, l.car FROM buyers b JOIN london l ON b.id = l.id
) data
WHERE car = 'Honda';
答案 2 :(得分:0)
您可以尝试以下查询:
select * from (
SELECT b.id, b.seller, p.car
FROM buyers b
JOIN paris p
ON b.id = p.id
UNION ALL
SELECT b.id, b.seller, l.car
FROM buyers b
JOIN london l
ON g.id = l.id;
)
where car = 'HONDA'
答案 3 :(得分:0)
万一这是你的真实数据库(我很确定它不是),这里有一些建议:
buyer_id
等。cars
。如果它真的只与品牌有关,那么更好的名称将是brands
或car_brands
等。以下是有关如何设计数据库的示例:
<强>汽车强>
id_car | name -------+------- 1 | BMW 2 | Ford 3 | Honda 4 | Toyota
<强>卖家强>
id_seller | name ----------+------ 0 | Paul 1 | Jean 2 | David 3 | Jack 4 | John 5 | Fred 6 | Peter
<强> Sellers_Cars 强>
id_seller | id_car ----------+------- 0 | 1 0 | 2 0 | 4 1 | 1 2 | 3 3 | 2 4 | 1 5 | 3 6 | 3 6 | 4
可能的查询:
select name as honda_seller
from sellers
where id_seller in
(
select id_seller
from sellers_cars
where car_id = (select car_id from cars where name = 'Honda')
);