mysql内部连接多列

z0qdvdin  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(352)

我有两张table
表1:违规列:日期、时间、pdid、pname、v1、v2、v3、v4
从v1到v4都有一个整数值,对应于表2中的一个条目(id)。
表2:停车违规列:代码、节、说明、id
我需要根据pdid查询每个违规记录,并将每个“v1-v4”与p\u违规表中的列“id”匹配。

SELECT 
    parking.date,
    parking.time,
    parking.pname,
    parking_violations.code,
    parking_violations.section,
    parking_violations.description
FROM 
    parking
INNER JOIN parking_violations ON parking.v1=parking_violations.ID
WHERE 
    pdid=5

这将返回v1的正确记录,但我不知道如何也返回v2-v4,所有这些记录都是通过将值与id匹配来填充的。

nfzehxib

nfzehxib1#

对别名使用join multiple time,如下所示:

SELECT 
    parking.date,
    parking.time,
    parking.pname,
    parking_violations.code,
    parking_violations.section,
    parking_violations.description
FROM 
    parking
INNER JOIN parking_violations ON parking.v1=parking_violations.ID
inner join parking_violations a ON parking.v2=a.ID
inner join parking_violations b ON parking.v3=b.ID
inner join parking_violations c ON parking.v4=d.ID
WHERE 
    pdid=5
t3irkdon

t3irkdon2#

像@fa06 explain一样,您可以对同一个表使用多个联接,但是我将使用left join来代替内部联接,这样我就可以灵活地获取行,而不是所有vn都在表上有匹配的id。

SELECT 
    parking.date,
    parking.time,
    parking.pname,
    pv1.code,
    pv1.section,
    pv1.description,
    pv2.code,
    pv2.section,
    pv2.description,
    pv3.code,
    pv3.section,
    pv3.description,
    pv4.code,
    pv4.section,
    pv4.description
FROM
    parking
LEFT JOIN
    parking_violations AS pv1 ON pv1.ID = parking.v1
LEFT JOIN
    parking_violations AS pv2 ON pv2.ID = parking.v2
LEFT JOIN
    parking_violations AS pv3 ON pv3.ID = parking.v3
LEFT JOIN
    parking_violations AS pv4 ON pv4.ID = parking.v4
WHERE 
    parking.pdid = 5;

相关问题