车辆主表 car_message
car_ID(主键) carnum
1 赣A3000
2 豫A8888
司机主表 driver_message
driver_id(主键) name
1 刘明
2 吴泽
中间表 car_driver
driver_id(主键1) car_id(主键2)
1 1
1 2
2 1
2 2
加油记录表 car_ref
id(主) car_id driver_id time
1 1 1 2017-03-23
怎么让加油记录表显示成这样子
赣A3000 刘明 2017-03-23
select c.name,b.carnum,a.time from car_ref a inner join car_message b on a.car_id=b.car_id
inner join driver_message c on a.driver_id=c.driver_id
不需要第三个表 car_driver 直接关联查询
后来。。我自己写出来了
select * from car_message t1,car_message t2 left join car_driver t3 on t3.driver_id=t1.driver_id and t3.car_id=t2.carid left join car_ref t4 on t4.car_id=t2.car_id and t4.driver_id=t1.driver_id
没运行过 参考
SELECT c.name,b.carnum,d.time FROM dbo.car_driver a
INNER JOIN dbo.car_message b ON a.car_ID=b.car_ID
INNER JOIN dbo.driver_message c ON a.driver_id=c.driver_id
INNER JOIN dbo.car_ref d ON a.car_ID=d.car_ID AND d.driver_id = a.driver_id
1、要构成结果,不需要第三个表 car_driver的。
2、这就是简单的 join 操作,不懂得话,建议还是找本SQL书好好学习一下吧。
这基本是程序员一年以内就该懂的知识。也基本是最简单最容易学习的编程知识了。
我刚刚写的时候怎么觉得怪怪的,现在仔细一看,原来如此,没仔细看清楚就开始写sql真的很不好,谢谢指教
连表查询
select carnum , name, time
from car_ref ,driver_message, car_message
where car_message.car_ID=car_ref.car_id
and driver_message.driver_id=car_ref.driver_id
SELECT CMSG.carnum, DMSG.name,REF.time
FROM car_ref REF
LEFT JOIN car_driver DRI ON REF.driver_id = DRI.driver_id
LEFT JOIN driver_message DMSG ON DMSG.driver_id = DRI.driver_id
LEFT JOIN car_message CMSG ON DMSG.car_ID = REF.car_ID
就一个连表查询而已很简单的需求