条件JOIN基于列值

时间:2012-05-27 20:09:04

标签: mysql sql

我尝试根据事件类型有条件地将一个主事件表连接到另外三个。 select语句工作正常,并返回我期望的结果集,但是当我添加JOIN语句时,我收到一条错误,指出没有找到列别名:

SELECT 
event.type as type,
IF(type = 'birthday', event.target_id, NULL) as birthday_id,
IF(type = 'graduation', event.target_id, NULL) as graduation_id,
IF(type = 'wedding', event.target_id, NULL) as wedding_id
FROM event
LEFT OUTER JOIN birthday ON birthday_id = birthday.id
LEFT OUTER JOIN graduation ON graduation_id = graduation.id
LEFT OUTER JOIN wedding ON wedding_id = wedding.id

获取此错误:

  

未知栏' birthday_id'在' on条款'


更新: Ok Sebas刚刚表示您无法加入计算结果,在这种情况下,我的方法已关闭。那么做这样的事情的正确方法是什么?

3 个答案:

答案 0 :(得分:2)

SELECT 
    event.type as type,
    IF(type = 'birthday', birthday.id, NULL) as birthday_id,
    IF(type = 'graduation', graduation.id, NULL) as graduation_id,
    IF(type = 'wedding', wedding.id, NULL) as wedding_id
FROM 
    event
        LEFT OUTER JOIN birthday b  ON event.target_id = b.id
        LEFT OUTER JOIN graduation g    ON b.id IS NULL AND event.target_id = g.id
        LEFT OUTER JOIN wedding w   ON b.id IS NULL AND g.id IS NULL AND event.target_id = w.id

应该做的伎俩,给我反馈! RGDS。

编辑:查看IS NULL条件。我没有测试它,我想知道mysql是否会接受它!如果是,那么几乎只有必要的连接才能完成......

答案 1 :(得分:1)

您需要使用相同的字段event.target_id连接所有表,并且当您需要显示某些特定数据时,您可以在之前测试该类型。

示例:

SELECT 
event.type as type,
IF(type = 'birthday', birthday.birthday_id, NULL) as birthday,
IF(type = 'graduation', graduation.graduation_id, NULL) as graduation,
IF(type = 'wedding', wedding.wedding_id, NULL) as wedding
FROM event
LEFT OUTER JOIN birthday ON birthday_id = event.target_id
LEFT OUTER JOIN graduation ON graduation_id = event.target_id
LEFT OUTER JOIN wedding ON wedding_id = event.target_id

不是睾丸,但希望这有助于你澄清你的怀疑。

答案 2 :(得分:0)

Sebas答案是正确的,但无需为每个以前的连接检查IS NULL,您可以使用基于列的值来使其生效。我测试了这个及其工作原理。

SELECT 
    E.type AS type,
    IF(E.type = 'birthday', B.id, NULL) AS birthday_id,
    IF(E.type = 'graduation', G.id, NULL) AS graduation_id,
    IF(E.type = 'wedding', W.id, NULL) AS wedding_id
FROM event E 
    LEFT OUTER JOIN birthday B ON E.type = 'birthday' AND E.target_id = B.id
    LEFT OUTER JOIN graduation G ON E.type = 'graduation' AND E.target_id = G.id
    LEFT OUTER JOIN wedding W ON E.type = 'wedding' AND E.target_id = W.id