0

我有以下 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
(...)

似乎不起作用。怎样才能做到这一点?

4

2 回答 2

1

尝试在 select 语句中显式列出内部表的列名。像:

...(SELECT auto.ID autoid, auto.Whatever)....

然后在主选择中:

SELECT innertable.autoid ....
于 2010-02-05T13:09:33.790 回答
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' 
于 2010-02-05T13:12:13.270 回答