我有以下表格:
时间轴
id data_id pattern
1 1 add_card
2 1 add_post
3 2 upd_card
4 2 upd_post
卡
id name parent
1 cname1 1
2 cname2 4
3 cname3 5
发表
id name parent
1 pname1 8
2 pname2 9
3 pname3 3
我需要表格结果
**结果时间表**
id data_id pattern name parent
1 1 add_card cname1 1
2 1 add_post pname1 8
3 2 upd_card cname2 4
4 2 upd_post pname2 9
我的想法仅在IF或CASE声明中
SELECT id, data_id, pattern
(CASE parent
WHEN ‘add_card’ THEN (SELECT name.card,parent.card FROM card WHERE data_id.timeline = id.card)
WHEN ‘add_card’ THEN (SELECT name.post,parent.post FROM post WHERE data_id.timeline = id.post)
END)
FROM timeline
但这不是正确的语法,这只是我的猜测它看起来如何!
答案 0 :(得分:3)
使用LEFT OUTER JOIN
选择性地加入卡片或帖子表以及COALESCE
以在一列中获取生成的父/姓名信息:
SELECT timeline.id, timeline.data_id, timeline.pattern,
COALESCE (post.name, card.name) AS name,
COALESCE (post.parent, card.parent) AS parent
FROM timeline
LEFT OUTER JOIN card ON timeline.data_id = card.id
AND timeline.pattern IN ('add_card', 'upd_card')
LEFT OUTER JOIN post ON timeline.data_id = post.id
AND timeline.pattern IN ('add_post', 'upd_post')
您可以在此处查看结果:http://sqlfiddle.com/#!2/76d8cb/1/0
结果与您的示例结果不符,但您的示例结果似乎与您的数据不一致,因此我认为这样做的意思是什么。 (更新:我现在已经编辑了您的示例结果以与您的示例表保持一致。)
答案 1 :(得分:-1)
您似乎正在检查相同的值并执行两项不同的操作。
但是我想你可能想要这样的东西: -
SELECT timeline.id, timeline.data_id, timeline.pattern
CASE
WHEN timeline.pattern = 'add_card' THEN card.name
WHEN timeline.pattern = 'add_card' THEN post.name
ELSE NULL
END,
CASE
WHEN timeline.pattern = 'add_card' THEN card.parent
WHEN timeline.pattern = 'add_card' THEN post.parent
ELSE NULL
END
FROM timeline
LEFT OUTER JOIN card timeline.data_id = card.id
LEFT OUTER JOIN post timeline.data_id = post.id