如何在mysql中加入三个表?

时间:2013-06-03 04:07:29

标签: php mysql join

我有以下表格。我需要通过车辆选项加入车辆细节。一辆车可能有多个选项,如防盗,皮革内饰等。我尝试了左连接。但没有得到确切的结果。

My question:有没有办法只获得一行,无论选项有一个还是多个?意味着选项需要获得数组或其他形式。

**vehicle_det**

vdId | Mileage | Transmission | IntColour | selCategory | price | selDriveTrain | Fuel  
--------------------------------------------------------------------------------------


**vehicle_option_trans**

id | vehicleId | optionId
------------------------


**vehicle_options**

id | type
---------

查询架构 -

CREATE TABLE vehicle_det 
    (
     vdId  int auto_increment primary key, 
     Mileage  varchar(20), 
     Transmission  varchar(30)
    );

INSERT INTO vehicle_det
(Mileage, Transmission)
VALUES
('10', 'automatic'),
('12', 'automatic'),
('5', 'manual'),
('11', 'manual');  


CREATE TABLE vehicle_option_trans 
    (
     id  int auto_increment primary key, 
     vehicleId  varchar(20), 
     optionId  varchar(30)
    );

INSERT INTO vehicle_option_trans
(vehicleId, optionId)
VALUES
('1', '1'),
('1', '3'),
('1', '4'),
('2', '2');   


CREATE TABLE vehicle_options 
    (
     id  int auto_increment primary key, 
     type  varchar(20)    );

INSERT INTO vehicle_options
(type)
VALUES
('Power Roof'),
('Sun Roof'),
('Heated Mirrors'),
('Alloy Wheels');

SQLFIDDLE

提前致谢。

2 个答案:

答案 0 :(得分:2)

如果您希望每辆车只返回一行,并且有所有选项,则需要执行GROUP_CONCAT() http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat。这将返回逗号分隔的数组 -

SELECT
    vehicle_det.*, GROUP_CONCAT(vehicle_options.type) as options
FROM 
    vehicle_det  
LEFT JOIN 
    vehicle_option_trans 
ON
    vehicle_det.vdId = vehicle_option_trans.vehicleId 
LEFT JOIN
    vehicle_options 
ON
    vehicle_options.id = vehicle_option_trans.optionId
GROUP BY vehicle_det.vdId

使用您的sqlfiddle数据,返回

enter image description here

请参阅此sqlfiddle - http://sqlfiddle.com/#!2/290c4a/9

答案 1 :(得分:0)

试试这个

select veh.*,group_concat(opt.type) as type from vehicle_det as veh
left join vehicle_option_trans as trans on
trans.vehicleId = veh.vdID left join vehicle_options
as opt on opt.id= trans.optionId where veh.vdID = '1'