mysql中的条件联接表

时间:2019-05-06 09:26:30

标签: mysql

我有两个桌子。我想要这些表中guest_id 1允许和不允许的所有活动的列表。

第一张桌子

activity_name_id | activity_name |

    1                 Entry

    2                 Exit

    3                 Break

第二张桌子

allowed_guest_id | allowed_activity_name_id |
    1                 1
    2                 1
    1                 3
    2                 4

现在我想要结果

activity_name_id | activity_name |allowed_guest_id | allowed_activity_name_id |

    1                 Entry                1                 1

    2                 Exit                 null              2

    3                 Break                1                 3

我已经尝试过了。但是它仅返回两行。首先和最后。

select * from table_activity_name
    left join table_allowed_activity 
    on activity_name_id = allowed_activity_name_id
        where allowed_activity_guest_id = 1;

3 个答案:

答案 0 :(得分:2)

尝试

select ta.activity_name_id, ta.activity_name, tal.allowed_guest_id, tal.allowed_activity_name_id from table_activity_name as ta
left join table_allowed_activity  as tal
on ta.activity_name_id = tal.allowed_activity_name_id
and tal.allowed_activity_guest_id = 1;

或IN操作

select ta.activity_name_id, ta.activity_name, tal.allowed_guest_id, tal.allowed_activity_name_id from table_activity_name as ta
left join table_allowed_activity  as tal
on ta.activity_name_id = tal.allowed_activity_name_id
and tal.allowed_activity_guest_id in (1,2);

答案 1 :(得分:1)

将您的allowed_activity_guest_id = 1条件放在ON clause中,而不是where

select * from table_activity_name
    left join table_allowed_activity 
    on activity_name_id = allowed_activity_name_id
        and allowed_activity_guest_id = 1

答案 2 :(得分:0)

如果要将条件应用于左联接表列,则必须在相关的左联接表的ON子句中设置此条件

select * 
from table_activity_name
left join table_allowed_activity 
    on activity_name_id = allowed_activity_name_id 
        AND  allowed__guest_id = 1;

如果您在何处使用这些条件,查询将作为内部联接