左联接查询混淆了两个表

时间:2019-10-21 12:05:26

标签: sql left-join

感谢您阅读我的问题。请足够支持我!

我尝试使用连接LEFT JOINActivity_Table的{​​{1}}查询获得以下输出,但找不到正确的查询。

任何建议,帮助,指针欢迎!

enter image description here

enter image description here

enter image description here

4 个答案:

答案 0 :(得分:0)

您可以两次left join

select 
    a.activity_id,
    a.activity_name,
    cp.name pos_name,
    co.name op_name
from activity_table a
left join custom_field_table cp on cp.id = a.pos_id
left join custom_field_table co on co.id = a.op_id

答案 1 :(得分:0)

@Savi

select 
    activity_id, activity_name, a.name pos_name, b.name op_name 
from 
    activity_table, custom_field_table a , custom_field_table b  
where 
    pos_id=a.id and op_id=b.id 
order by activity_id

在上面,由于您使用的是公共参考表,因此需要对同一表进行两次连接。有两个不同的参考。希望这会有所帮助!

答案 2 :(得分:0)

您可以做2个关节:

Select Activity_id,Activity_name,tmp1.name as Pos_name,tmp2.name as op_name from Activity_table at
left join custom_field_table tmp1 on tmp1.id = at.pos_id
left join custom_field_table tmp2 on tmp2.id = at.op_id
order by activity_id

See the fiddle

答案 3 :(得分:0)

此查询将为您提供所需的输出。但是您需要对尝试的内容(要求)更加具体。

SELECT 
    x.* 
FROM (
    SELECT 
        a.activity_id, a.activity_name,
        IF(a.pos_id = b.id, b.name, null) AS pos_name,
        IF(a.op_id = b.id, b.name, null) AS op_name
    FROM 
        activity_table a 
    JOIN
        custom_field_table b 
) x
WHERE 
    x.pos_name IS NOT NULL AND x.op_name IS NOT NULL;

但是,由于没有任何连接条件,因此上面的查询将是交叉连接。 (在此查询中)where子句将确保您仅获得pos_name和op_name都不为空的行。