小编典典

MySQL多个联接一个查询?

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

如何将其添加到查询中?


阅读 259

收藏
2020-05-17

共1个答案

小编典典

您可以简单地添加另一个联接,如下所示:

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
2020-05-17