一个查询中的 MySQL 多个连接? [英] MySQL Multiple Joins in one query?

查看:44
本文介绍了一个查询中的 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 

这篇关于一个查询中的 MySQL 多个连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆