我有两个桌子
表1:违规 列:日期,时间,pdid,pname,v1,v2,v3,v4
每个v1到v4具有一个整数值,该整数值对应于表2中的单个条目(ID)。
表2:parking_violations 列:代码,部分,说明,ID
我需要基于pdid查询每个违规记录,并将每个“ v1-v4”与p_violations表中的“ 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的正确记录,但是我无法弄清楚如何还通过将值与ID匹配来返回所有填充的V2-V4。
答案 0 :(得分:0)
使用别名多次连接,如下所示:
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
答案 1 :(得分:0)
就像@ fa06解释的那样,您可以对同一张表使用多个联接,但是我将使用左联接,而不是内部联接,这样我就可以灵活地获取并非所有 vN 都在表parking_violations上具有匹配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;