MySQL Multiple Joins in one query?

后端 未结 4 799
执念已碎
执念已碎 2020-12-02 05:45

I have the following query:

SELECT
  dashboard_data.headline,
  dashboard_data.message,
  dashboard_messages.image_id 
FROM dashboard_data
INNER JOIN dashboa         


        
4条回答
  •  孤城傲影
    2020-12-02 06:19

    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 
    

    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 
    

提交回复
热议问题