mysql - 如果一个键值应该或不应该在一个表中,如何连接三个表?

标签 mysql sql

我正在尝试设计一个应用程序,我想在其中获取值 或者使用查询条件, 我有三个表:文本、图像、音频,每个表中的complaint_id列都是相同的。

注意:表格文本中插入的记录是强制性的。

但对于图像和音频,它可能会也可能不会插入记录 (因为这取决于用户是否插入图像或音频)

表格:文本

complaint_id | text_note
------------------------
   34556     | Hello
   34557     | welcome  

表:图像

complaint_id | photo_link
-----------------------------
   34556     | photo_link

表:音频

complaint_id | audio_link
----------------------------
   34557     | audio_link

我想要输出为

complaint_id | text_note | photo_link     | audio_link
------------- ----------- ---------------- --------------
34556        |  Hello    | photo_link     |
34557        |  welcome  |                | audio_link

我设计了一个查询,但它不适合我!

SELECT
    *
FROM
    test t
JOIN image i ON (
    t.complaint_id = i.complaint_id
)
JOIN audio a ON (
    t.complaint_id = a.complaint_id
)
GROUP BY
    t.complaint_id

最佳答案

SELECT
    complaint_id,
    IFNULL(text_note, '') text_note,
    IFNULL(photo_link, '') photo_link,
    IFNULL(audio_link, '') audio_link
FROM
    text
LEFT OUTER JOIN image ON text.complaint_id = image.complaint_id
LEFT OUTER JOIN audio ON text.complaint_id = audio.complaint_id

关于mysql - 如果一个键值应该或不应该在一个表中,如何连接三个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40925513/

相关文章:

php - sql中的if else子句,自动重建索引

php - 列出数据库表关系及其类型

mysql - 更新表,将每一行从最大值增加 1

mysql - 尝试编写一个查询来获取最高和最低收入并打印帐户健康状况?

SQL Server - 从 2 列中获取不同的 ID 并存储在一个列表中

mysql - 在 mysql 列中使用另一个查询

php - 在Mysql上选择IF EXISTS THEN ELSE

sql - 间接 UNIQUE 约束

php - Docker 没有 MySQL 连接到 Nginx

sql - mySQL JOIN 语句未返回我想要的内容