我有一个CASE语句的查询来确定变量object_name
该变量来自x_ambitions
表或x_trybes
表。下面的查询被合并,以便我可以通过执行一个SQL查询来简化它。返回NULL的MySQL CASE LEFT JOINS
我把SELECT语句分成了两个,这样你就可以更好地理解了。下面的两个查询。工作并从数据库中提取正确的object_name。
当我组合两个查询时遇到的问题是'new_join_ambition','new_created_ambition','new_liked_ambition'
object_name在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?如果您有任何问题,请使用评论,我会毫不犹豫地回复。
在此先感谢
你可以做一个小提琴。并发布准确的预期输出 – amdixon