Left根据可能缺失的条件加入SQL

时间:2011-06-23 22:44:05

标签: sql join

我有几个表要为一个大查询合并。搜索条件基于两个表:section_typessections。我想提取所有section_types及其关联的sections,其中sections符合某些条件,加上任何有效section_types但没有sections的{​​{1}}相关。这似乎是一个基本的LEFT JOIN,但我认为因为我的某些过滤条件基于sections,我无法获得没有关联section_types的{​​{1}}

sections

假设我想在位置1处提取问题0611的所有部分,以及任何空的部分类型。像这样:

(编辑。见下文)

但我只会`section_types` id | name | active ---+------+------- 1 | a | 1 2 | b | 0 3 | c | 1 `sections` type | issue | location -----+-------+---------- 1 | 0611 | 1 2 | 0611 | 1 1 | 0511 | 1 得到相应的section_types。因此,在此查询中,sections第3行不会显示。我做错了什么?

编辑:

我现在收到所有section_types,但不是我需要的所有section_types。我猜sections会这样做。每个LEFT JOIN可以有多个sections,或者没有。我现在的询问是:

section_type

让我:

SELECT * FROM `section_types` st
    RIGHT JOIN `sections` s
        ON s.type=st.id
            AND s.issue='0611'
            AND s.location=1
WHERE st.active OR s.issue IS NOT NULL
ORDER BY st.id

但我仍然需要第二种类型1 id | name | active | issue | location ---+------+--------+-------+--------- 1 | a | 1 | 0611 | 1 2 | b | 0 | 0611 | 1 3 | c | 1 | |

3 个答案:

答案 0 :(得分:1)

修改

我删除了这个,但根据对话,我认为它可以完成您正在寻找的内容。

<强> ORIGINAL

感觉像是黑客......但我认为它有效。

Declare @tmp TABLE(
    id int,
    name varchar(50),
    active int,
    type int,
    issue int,
    location int
)
Insert Into @tmp
SELECT * FROM section_types st
    LEFT JOIN sections s
        ON st.id=s.type
            AND s.issue='0611'
            AND s.location=1 
WHERE st.active = 1 OR s.issue IS NOT NULL
ORDER BY st.id

Select * FROM @tmp 
UNION 
Select 
    *, NULL, NULL, NULL 
From 
    section_types 
WHERE 
    id NOT IN ( SELECT id FROM @tmp)
    AND active = 0

答案 1 :(得分:0)

你的桌子反转了。 LEFT OUTER JOIN要求 left 表为ON条件设置一行。使用RIGHT OUTER JOIN或交换表格。

答案 2 :(得分:0)

这是你需要的吗?

所有section_types及其相关部分,其中至少有一个部分有问题'0611'和地点1。加上所有其他活跃的section_types:

    SELECT *
    FROM section_types st
        JOIN sections s
            ON s.type = st.id
    WHERE EXISTS
        ( SELECT *
            FROM sections s2
            WHERE s2.type = st.id
              AND s2.issue = '0611'
              AND s2.location = 1
        ) 
UNION ALL
    SELECT *, NULL, NULL, NULL
    FROM section_types st
    WHERE st.active
      AND NOT EXISTS
        ( SELECT *
            FROM sections s2
            WHERE s2.type = st.id
              AND s2.issue = '0611'
              AND s2.location = 1
        ) 
ORDER BY id