MySQL多个连接在一个查询中?

时间:2012-01-23 15:46:13

标签: mysql sql join

我有以下查询:

SELECT
  dashboard_data.headline,
  dashboard_data.message,
  dashboard_messages.image_id 
FROM dashboard_data
INNER JOIN dashboard_messages
  ON dashboard_message_id = dashboard_messages.id

所以我正在使用INNER JOIN并抓住image_id。所以现在,我想把image_id从图像表中转换为images.filename

如何将其添加到我的查询中?

4 个答案:

答案 0 :(得分:171)

你可以简单地添加另一个这样的连接:

SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data 
    INNER JOIN dashboard_messages 
        ON dashboard_message_id = dashboard_messages.id
    INNER JOIN images
        ON dashboard_messages.image_id = images.image_id 

但请注意,因为它是INNER JOIN,如果您有没有图像的消息,则会跳过整行。如果有可能,您可能需要执行LEFT OUTER JOIN,它将返回所有仪表板消息和image_filename(如果存在)(否则您将获得空值)

SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data 
    INNER JOIN dashboard_messages 
        ON dashboard_message_id = dashboard_messages.id
    LEFT OUTER JOIN images
        ON dashboard_messages.image_id = images.image_id 

答案 1 :(得分:9)

只需添加另一个联接:

SELECT dashboard_data.headline,
       dashboard_data.message,
       dashboard_messages.image_id,
       images.filename 
FROM dashboard_data 
    INNER JOIN dashboard_messages
            ON dashboard_message_id = dashboard_messages.id 
    INNER JOIN images
            ON dashboard_messages.image_id = images.image_id

答案 2 :(得分:8)

我分享了在单个SQL查询中使用两个LEFT JOINS的经验。

我有3张桌子:

表1)患者包括栏目PatientID,PatientName

表2)约会包括列AppointmentID,AppointmentDateTime,PatientID,DoctorID

表3)医生包括列DoctorID,DoctorName


查询:

SELECT Patient.patientname, AppointmentDateTime, Doctor.doctorname

FROM Appointment 

LEFT JOIN Doctor ON Appointment.doctorid = Doctor.doctorId  //have doctorId column common

LEFT JOIN Patient ON Appointment.PatientId = Patient.PatientId      //have patientid column common

WHERE Doctor.Doctorname LIKE 'varun%' // setting doctor name by using LIKE

AND Appointment.AppointmentDateTime BETWEEN '1/16/2001' AND '9/9/2014' //comparison b/w dates 

ORDER BY AppointmentDateTime ASC;  // getting data as ascending order

我写了解决方案来获取date format like "mm/dd/yy"(在我的名下" VARUN TEJ REDDY")

答案 3 :(得分:0)

SQL中的多重联接通过一个接一个的逐步创建派生表来进行。 请参阅此链接以说明过程:

https://www.interfacett.com/blogs/multiple-joins-work-just-like-single-joins/