且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-22 13:37:34

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

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