我有一个带有CASE语句的查询,该语句确定变量object_name
此变量是从x_ambitions
表或x_trybes
表派生的。下面的查询被组合在一起,这样我只需执行一个SQL查询就可以保持简单。
我已将SELECT语句拆分为两个,以便您更好地理解。以下两个查询。工作并从数据库中提取正确的object_name。
我在组合两个查询时遇到的问题是'new_join_ambition','new_created_ambition','new_liked_ambition'
个对象在LEFT JOIN
中返回NULL。
在合并查询中,如果我将案例'new_join_ambition','new_created_ambition','new_liked_ambition'
置于'new_join_trybe','new_created_trybe','new_liked_trybe'
个案例之上。相反的情况发生了trybe行返回NULL
。
两个SQL查询:
答:(检索对象A)
SELECT
s.id,
s.object_id,
s.type,
s.postee_id,
s.user_id,
s.text,
s.registered,
CONCAT(u.x_first_name,' ',u.x_last_name) AS postee_name,
ui.image_id AS postee_image_id,
CASE s.type
WHEN 'new_join_ambition'
OR 'new_created_ambition'
OR 'new_liked_ambition'
THEN a.name
ELSE 'a'
END AS object_name
FROM
x_share s
LEFT JOIN
x_user u ON u.id = s.postee_id
LEFT JOIN
x_user_images ui ON ui.user_id = s.postee_id
LEFT JOIN
x_ambitions a ON s.type IN ('new_join_ambition', 'new_created_ambition', 'new_liked_ambition') AND s.object_id = a.id
LEFT JOIN
x_ambition_invites ai ON s.type IN ('new_join_ambition') AND s.object_id = ai.ambition_id AND s.postee_id = ai.to
LEFT JOIN
x_ambition_likes al ON s.type IN ('new_liked_ambition') AND s.object_id = al.ambition_id AND s.postee_id = al.profile_id
LEFT JOIN
x_ambition_owner aoo ON s.type IN ('new_created_ambition') AND s.object_id = aoo.ambition_id
WHERE
s.user_id = '%s'
ORDER BY
s.registered DESC
B :(检索对象B)
SELECT
s.id,
s.object_id,
s.type,
s.postee_id,
s.user_id,
s.text,
s.registered,
CONCAT(u.x_first_name,' ',u.x_last_name) AS postee_name,
ui.image_id AS postee_image_id,
CASE s.type
WHEN 'new_join_trybe'
OR 'new_created_trybe'
OR 'new_liked_trybe'
THEN t.name
ELSE 'a'
END AS object_name
FROM
x_share s
LEFT JOIN
x_user u ON u.id = s.postee_id
LEFT JOIN
x_user_images ui ON ui.user_id = s.postee_id
LEFT JOIN
x_trybes t ON s.type IN ('new_join_trybe', 'new_created_trybe', 'new_liked_trybe') AND s.object_id = t.id
LEFT JOIN
x_trybe_invites ti ON s.type IN ('new_join_trybe') AND s.object_id = ti.trybe_id AND s.postee_id = ti.to
LEFT JOIN
x_trybes_likes tl ON s.type IN ('new_liked_trybe') AND s.object_id = tl.trybe_id AND s.postee_id = tl.profile_id
LEFT JOIN
x_trybe_owner too ON s.type IN ('new_created_trybe') AND s.object_id = too.trybe_id
WHERE
s.user_id = '%s'
ORDER BY
s.registered DESC
我已经运行了两个查询并捕获了两个查询结果的图像。
设置A:
设置B:
如何在没有object_name返回NULL的情况下组合这两个?如果您有任何疑问,请使用评论,我会毫不犹豫地回复。
提前致谢
答案 0 :(得分:2)
我不知道您的查询的其余部分,但您的case
声明不正确。你有:
(CASE s.type
WHEN 'new_join_ambition' OR 'new_created_ambition' OR 'new_liked_ambition'
THEN a.name
ELSE 'a'
END) AS object_name
OR
最终将值视为数字,因此相当于WHEN 0 THEN . . .
。
你想要的是这种形式的case
:
(CASE WHEN s.type IN ('new_join_ambition', 'new_created_ambition', 'new_liked_ambition')
THEN a.name
ELSE 'a'
END) AS object_name