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

2021-12-17 00:00:00 join sql 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 .

So I am using an INNER JOIN and grabbing the image_id. So now, I want to take that image_id and turn it into images.filename from the images table.

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

How can I add that in to my query?

推荐答案

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

You can simply add another join like this:

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,仅当存在一个时(否则您将得到一个空值)

However be aware that, because it is an INNER JOIN, if you have a message without an image, the entire row will be skipped. If this is a possibility, you may want to do a LEFT OUTER JOIN which will return all your dashboard messages and an image_filename only if one exists (otherwise you'll get a 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 

相关文章