在一个查询MySQL多重连接?
我有以下查询:
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
。
我怎样才能添加到我的查询?
你可以简单地添加这样的另一个连接:
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
只需添加另一个连接:
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查询中使用两个LEFT JOIN的经验。
我有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
我写了解决scheme来获取date格式,如“mm / dd / yy” (以我的名字“VARUN TEJ REDDY”)