简体   繁体   English

MySQL加入一对多关系的语法

[英]MySQL Join syntax for one to many relationship

I have a situation where I have one table of titles (t1) and another table with multiple links that reference these titles (t2) in a one to many relationship. 我有一种情况,我有一个标题表(t1)和另一个表有多个链接,以一对多的关系引用这些标题(t2)。

What I want is the full list of titles returned with a flag that indicates if there is a specific link associated with it. 我想要的是返回的标题的完整列表,其中包含一个标志,指示是否存在与之关联的特定链接。

Left Join and Group By: 左加入和分组依据:

SELECT
    t1.id
    , t1.title
    , t2.link_id AS refId
FROM
    t1
    LEFT JOIN t2
        ON (t1.id = t2.title_id)
GROUP BY t1.id;

This is close as it gives me either the first link_id or NULL in the refId column. 这很接近,因为它在refId列中给出了第一个link_id或NULL。

Now, how do I constrain the results if I have a specific link_id rather than allowing t2 run through the whole data set? 现在,如果我有一个特定的link_id而不是允许t2运行整个数据集,我如何约束结果?

If I add a WHERE clause, for example: 如果我添加一个WHERE子句,例如:

WHERE t2.link_id = 123

I only get the few records where the link_id matches but I still need the full set of titles returned with NULL in the refId column unless link_id = 123. 我只获得了link_id匹配的几条记录,但我仍然需要在refId列中返回NULL的完整标题集,除非link_id = 123。

Hope someone can help 希望有人能提供帮助

Instead of in the WHERE clause, put your criteria in the LEFT JOIN clause: 而不是在WHERE子句中,将您的条件放在LEFT JOIN子句中:

SELECT
    t1.id
    , t1.title
    , t2.link_id AS refId
FROM
    t1
    LEFT JOIN t2
        ON t1.id = t2.title_id AND t2.link_id = 123
GROUP BY t1.id;

Put it in the join condition for the second table 将它放在第二个表的连接条件中

SELECT t1.id, t1.title, t2.link_id as refId
FROM t1
LEFT JOIN t2 ON t1 = t2.title_id AND t2.link_id = 123
GROUP BY t1.id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM