MySQL在一个查询中有多个连接?
我有以下疑问:MySQL在一个查询中有多个连接?,mysql,sql,join,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 因此,我使用内部连接并获取图像\u id。现在,我想获取该图像的id,并将其从images表中转换为
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
因此,我使用内部连接
并获取图像\u id
。现在,我想获取该图像的id,并将其从images表中转换为images.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
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
但是,请注意,由于它是一个内部联接
,如果您有一条没有图像的消息,则将跳过整行。如果这是一种可能性,您可能希望执行左外部联接
,该联接将返回所有仪表板消息和图像文件名(如果存在)(否则将得到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
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
我分享了在一个SQL查询中使用两个左连接的经验 我有三张桌子: 表1)Patient由PatientID、PatientName列组成 表2)预约由AppointId、AppointDateTime、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
我编写了一个解决方案(以我的名字“VARUN TEJ REDDY”)通过一个接一个地逐步创建派生表来获取SQL工作中的多连接。 请参阅此链接以解释此过程:
有人知道这是怎么回事吗?第二个联接是将第一个联接的结果与表3联接,还是将表1与表3分别联接?(即,将表1与表2连接,然后将表1与表3单独连接,然后将其全部返回)这有意义吗?我这样问是因为我一直在做这样的多表联接,有时会得到意想不到的结果。第二次联接(联接第三个表)的ON子句将仪表板_消息联接到每个表的image_id字段上的图像。所以,在这种情况下,是A到B,然后是B到C,它在你的控制之下。如果你需要经常引用一个重要链接中最相关的部分,你可以把它改为A到B和A到C,以防目标站点无法访问或永久脱机。
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