0

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

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

提前致谢。

4

2 回答 2

2

如果您只想为每辆车返回一行及其所有选项,则需要执行http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-连接。这将返回一个逗号分隔的数组 -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 数据,这将返回

在此处输入图像描述

看到这个 sqlfiddle - http://sqlfiddle.com/#!2/290c4a/9

于 2013-06-03T04:54:40.490 回答
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'
于 2013-06-03T05:13:28.827 回答