MySQL多个联接一个查询?


121

我有以下查询:

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从图像表中转换成。

如何将其添加到查询中?


Answers:


209

您可以像这样简单地添加另一个联接:

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(否则,您将获得null)

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 

19
有人知道这实际上是如何工作的吗?第二个联接是将第一个联接与表3的结果联接在一起,还是将表1和表3分别​​联接?(即,将表1与表2连接起来,然后将表1与表3分别连接起来,然后全部归还吗?)这有意义吗?我问是因为我一直在进行这样的多表联接,有时会得到意想不到的结果。
亚伦·瓦伦丁

3
这就是ON子句将告诉您的。第二次联接(联接第三张表)的ON子句将dashboard_messages联接到每个表中image_id字段上的图像。因此,在这种情况下,是A到B,然后是B到C。这在您的控制之下。您可以根据需要将其设置为A到B以及A到C
John Biddle

16

只需添加另一个联接:

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

9

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

我有3张桌子:

表1)患者组成列PatientID,PatientName

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

表3)Doctor包含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

我写了解决方案以获取日期格式,例如“ mm / dd / yy”(以我的名字“ VARUN TEJ REDDY”命名)


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.