从CASE中的不同行返回值

时间:2016-07-14 10:34:18

标签: mysql

我不知道是否有可能,但我想我可以问

我有一个家庭和子系列表(family_table):

family_id  family_name     parent_id
1          Family 1        null
2          Family 2        null
3          Subfamily 1.1   1   
4          Subfamily 1.2   1
5          Family 3        null
6          Subfamily 2.1   2 

然后我有一个复杂的SELECT返回一些family_id,比如2,4。

然后我需要返回以下信息:

principal_id  family_name     subfamily_id   subfamily_name
2             Family 2        null           null
1             Family 1        4              Subfamily 1.2

编辑:我不介意改变结果的显示方式或改变其他内容,只要它足够清晰。

这是我到目前为止所做的事情:

SELECT
    CASE
WHEN ft.parent_id IS NULL THEN
    ft.family_id
ELSE
    ft.parent_id
END AS principal_id, 
/*I was thinking something like this, but I don't know how to select another row value here, or if there would be another way
CASE
WHEN ft.parent_id IS NULL THEN
    ft.family_name
ELSE
    *Family name from the parent*
END AS family_name*/
FROM
    family_table ft
LEFT JOIN family_table ft2 ON ft2.parent_id = ft.family_id
WHERE
    ft.family_id IN (2,4/*complicated select*/)

编辑:这个以下的尝试工作,因为它回归家庭作为一个家庭的结果,它并没有加入我所需要的子系列的父ID。 /强>

也许是这样的:

SELECT
    ft.family_id as principal_id,
    ft.family_name as family_name,
    ft2.family_id as subfamily_id,
    ft2.family_name as subfamily_name
FROM ft.family_table
LEFT JOIN ft2.family_table ON ft2.parent_id = ft.family_id
WHERE
    /*ft.family_id OR ft2.parent_id*/ IN (2,4/*complicated select*/)

我不想通过ft.family_id IN (2,4/*complicated select*/) OR cf2.parent_id IN (2,4/*complicated select*/)重复这个怪异的选择。 我觉得我的一切都太复杂了......

这里是最终的查询,将接受的答案记录在帐户中(如果有人想知道的话)

SELECT
    COALESCE (ft2.family_id, ft.family_id) AS family_id,
    COALESCE (ft2.family_name, ft.family_name) AS family_name,
    CASE WHEN ft.parent_id IS NOT NULL THEN ft.family_id
    END AS subfamily_id,
    CASE WHEN ft.parent_id IS NOT NULL THEN ft.family_name
    END AS subfamily_name
FROM family_table ft
JOIN (/* complicated select */) AS t ON t.family_id IN (ft.family_id, ft.parent_id)
LEFT JOIN family_table ft2 ON ft2.family_id = ft.parent_id

1 个答案:

答案 0 :(得分:2)

尝试加入“复杂选择”而不是使用IN(),如下所示:

SELECT
.....
FROM
    family_table ft
LEFT JOIN family_table ft2 ON ft2.parent_id = ft.family_id
JOIN ( /* complicated select here */ ) t
 ON(t.ID_OR_WHATEVER IN(ft.family_id,cf2.parent_id))

这将产生同样的效果。