我有以下SQL语句:
SELECT *
FROM cars car
LEFT JOIN (SELECT *
FROM cars auto
LEFT JOIN steeringwheels sw
ON auto.steeringwheelid = sw.ID
WHERE material = 'leather') innertable
ON innertable.ID = car.ID
LEFT JOIN steeringwheels sw
ON auto.steeringwheelid = sw.ID
WHERE sw.material='plastic'
此查询提供表“Cars”中的列两次,但是来自Car表的ID具有不同的值(查询的目的是映射值以查看Car.ID将ID为材料的内容将从皮革变为塑料)。
------------------------------------
| ID | material | ID_1 | material_1 |
-------------------------------------
| 1 | leather | 4 | plastic |
| 2 | leather | 7 | plastic |
-------------------------------------
但是,我想只输出ID列(而不是材料列),如下所示:
-------------
| ID | ID_1 |
-------------
| 1 | 4 |
| 2 | 7 |
-------------
我无法做到这一点,因为我没有找到以任何方式引用内部查询的ID列的方法。例如
SELECT id, innertable.id
(...)
或
SELECT id, auto.id
(...)
或
SELECT id, id_1
(...)
似乎没有用。怎么能实现这个目标?
答案 0 :(得分:1)
尝试在select语句中显式列出内部表的列名。像:
...(SELECT auto.ID autoid, auto.Whatever)....
然后在主要选择:
SELECT innertable.autoid ....
答案 1 :(得分:1)
这就是你要追求的吗?
SELECT auto_id, steeringwheel_id
FROM cars car
LEFT JOIN (SELECT auto.ID AS auto_id, sw1.id AS steeringwheel_id
FROM cars auto
LEFT JOIN steeringwheels sw1
ON auto.steeringwheelid = sw1.ID
WHERE material = 'leather') innertable
ON innertable.auto_ID = car.ID
LEFT JOIN steeringwheels sw2
ON auto.steeringwheelid = sw2.ID
WHERE sw.material='plastic'