4

我正在尝试根据事件类型有条件地将一个主事件表连接到其他三个事件表。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

得到这个错误:

“on 子句”中的未知列“birthday_id”


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

4

3 回答 3

5
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会不会接受!如果是,那么几乎只会完成必要的连接......

于 2012-05-27T20:18:08.143 回答
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

不是睾丸,但希望这能帮助你澄清你的疑虑。

于 2012-05-27T20:18:14.977 回答
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 
于 2018-04-25T12:24:20.020 回答