使用父属性的Mysql查询

时间:2017-12-13 17:22:56

标签: mysql sql select

我有三张桌子:

类:

|Id | TopId|
| 1 | null |
| 2 | null |
| 3 |  1   |
| 4 |  1   |
| 5 |  2   |
| 6 |  3   |

等...

categorycultures:

|Id|CultureOf|CultureId|Name      |
|1 |    1    |    1    |Category 1|
|2 |    1    |    2    |Klasse   1|
|3 |    1    |    3    |Kategori 1|
|4 |    2    |    1    |Category 2|
|5 |    2    |    2    |Klasse   2|
|6 |    2    |    3    |Kategori 2|

CultureOf也意味着:CategoryId 等...

文化

|Id|Name|Flag          |    
|1 |en  |/images/en.png|    
|2 |de  |/images/de.png|    
|3 |tr  |/images/tr.png|

并且这个sql脚本正在获得我需要的东西,但没有null top id。

select c.Id as Id, cp.Id as TopId, cc.Name as Name, ccp.Name as TopName,    cul.Id as CultureId, cul.Name as CultureName

from categories as c

inner join categories as cp on c.TopId = cp.Id 

inner join categorycultures as cc on cc.CultureOf = c.Id

inner join categorycultures as ccp on ccp.CultureOf = cp.Id

inner join cultures as cul on cul.Id = cc.CultureId and cul.Id = ccp.CultureId

where cul.Id = 2

结果是:

results

缺少那些TopId为空的行

我在cp的内部联接系列中尝试了很多案例并尝试了很多脚本,但我无法获得正确的值。

2 个答案:

答案 0 :(得分:0)

试试这个

将文化加入文化

答案 1 :(得分:0)

这很有用。但我什么都没学到我会复制&粘贴下次我需要这个。

select c.Id as Id, c.TopId as TopId, cc.Name as Name, CASE
WHEN c.TopId is null THEN "none" 
ELSE ccp.Name
END as TopName, cul.Id as CultureId, cul.Name as CultureName

from categories as c

left join categories as cp on CASE
    WHEN c.TopId is null THEN "null" 
    ELSE c.TopId = cp.Id
END

inner join categorycultures as cc on cc.CultureOf = c.Id

left join categorycultures as ccp on ccp.CultureOf = cp.Id

left outer join cultures as cul on cul.Id = cc.CultureId and CASE
    WHEN c.TopId is null THEN 1 
    ELSE cul.Id = ccp.CultureId 
END

where cul.Id = 1