在同一个JOIN中的同一个表中选择多个行

时间:2017-12-09 01:18:24

标签: mysql sql join

图中是我现在的情况:

Table 这个案例中的中央表现在是tblJob,这里是我需要的所有内容(图片中不是全部)。

地址表需要返回2个值(公司的1个和作业本身的1个)。我现在唯一需要做的就是添加公司地址(工作地址已经在我的查询中)我的查询看起来像这样:

SELECT
tblJob.jobID,
tblJob.amount        AS jobAmount,
tblJob.extraInfo     AS jobExtraInfo,
tblJob.views         AS jobViews,
tblJob.description   AS jobDescription,
tblJob.dateCreated   AS jobDateCreated,
tblJobFunction.jobFunctionID,
tblJobFunction.jobFunction,
tblAddress.zipcode   AS jobAddress,
tblAddress.city      AS jobCity,
tblAddress.street    AS jobStreet,
tblAddress.number    AS jobNumber,
tblAddress.bus       AS jobBus,
tblCountry.countryID AS jobCountryID,
tblCountry.country   AS jobCountry,
tblCountry.areaCode  AS jobAreaCode,
tblCompany.companyID,
tblCompany.name,
tblCompany.email,
tblCompany.GSM,
tblCompany.phoneNumber,
tblCompany.photoURL  AS companyPhotoURL,
tblCompany.VATNumber,
tblCompany.websiteURL,
tblEvent.eventID,
tblEvent.event,
tblEvent.description AS eventDescription,
tblEvent.startDate   AS eventStartDate,
tblEvent.endDate     AS eventEndDate,
tblEvent.facebookURL,
tblEvent.photoURL    AS eventPhotoURL,
tblEvent.views       AS eventViews,
tblEvent.dateCreated AS eventDateCreated
FROM tblJob
JOIN tblAddress ON tblAddress.addressID = tblJob.addressID
JOIN tblCountry ON tblAddress.countryID = tblCountry.countryID
JOIN tblJobFunction ON tblJob.jobFunctionID = 
                       tblJobFunction.jobFunctionID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID
LEFT JOIN tblEvent ON tblJob.eventID = tblEvent.eventID

现在问题是:如何在同一个查询中添加公司地址?

1 个答案:

答案 0 :(得分:2)

根据需要多次使用地址表,但每次必须为其添加新别名:

FROM tblJob
JOIN tblAddress ON tblAddress.addressID = tblJob.addressID
JOIN tblCountry ON tblAddress.countryID = tblCountry.countryID
JOIN tblJobFunction ON tblJob.jobFunctionID =  tblJobFunction.jobFunctionID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID

JOIN tblAddress a2 ON a2.addressID = tblCompany.addressID

LEFT JOIN tblEvent ON tblJob.eventID = tblEvent.eventID

或许更像这样:

SELECT JobAddress.street, CompanyAddress.street
FROM tblJob
JOIN tblAddress JobAddress ON JobAddress.addressID = tblJob.addressID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID
JOIN tblAddress CompanyAddress ON CompanyAddress.addressID = tblCompany.addressID