我有1个字符串类型的表。 (photo_add,photo_comment等) 然后我有4个与这些类型相关的其他表。
我需要进行一个查询,根据类型从所有这些表中选择数据。
我创建了这个,但它不起作用。
SELECT DISTINCT a.id, a.event, a.params, a.created_at, a.item_id, a.sender_id, a.receiver_id, u.name, u.id as userid
FROM `eva49_lovefactory_activity` a, eva49_users u
CASE a.event
WHEN "photo_add" THEN
INNER JOIN eva49_lovefactory_photos lp ON lp.id = a.item_id AND lp.fsk18 = -1
WHEN "group_create" THEN
INNER JOIN eva49_lovefactory_groups lg ON lg.id = a.item_id AND lg.fsk18 = -1
WHEN "photo_comment" THEN
INNER JOIN eva49_lovefactory_item_comments lic ON lic.item_id = a.item_id AND lic.fsk18 = -1
WHEN "profile_comment" THEN
INNER JOIN eva49_lovefactory_item_comments lic ON lic.item_id = a.item_id AND lic.fsk18 = -1
WHEN "profile_comment" THEN
INNER JOIN eva49_lovefactory_profiles lp ON lp.user_id = a.receiver_id AND lp.status_fsk18 = -1
ELSE 1=1
END
WHERE (u.id = a.sender_id OR u.id = a.receiver_id) and (u.id <> 379)
ORDER BY a.created_at DESC LIMIT 0, 10
有没有办法配对桌子?数据库结构是这样给我的。
编辑:
有一个表“eva49_lovefactory_activity”,其中包含有关最近活动的信息。它有一个“事件”列,其中包含带有事件名称的字符串(photo_add,photo_comment等)。
还有其他表格 - eva49_lovefactory_photos,eva49_lovefactory_profiles,eva49_lovefactory_groups等。在这些表格中,我必须找到该项目是否得到了管理员的批准。如果是的话,我可以展示它。 (fsk18 = -1)
答案 0 :(得分:4)
将CASE条件移至JOIN条件并执行LEFT JOIN ..
SELECT DISTINCT a.id, a.event, a.params, a.created_at, a.item_id, a.sender_id, a.receiver_id, u.name, u.id as userid
FROM `eva49_lovefactory_activity` a, eva49_users u
LEFT JOIN eva49_lovefactory_photos lp ON lp.id = a.item_id AND lp.fsk18 = -1
AND a.event='photo_add'
LEFT JOIN eva49_lovefactory_groups lg ON lg.id = a.item_id AND lg.fsk18 = -1
AND a.event='group_create'
LEFT JOIN eva49_lovefactory_item_comments lic ON lic.item_id = a.item_id AND
lic.fsk18 = -1 AND a.event='photo_comment'
LEFT JOIN eva49_lovefactory_item_comments lic ON lic.item_id = a.item_id AND
lic.fsk18 = -1 AND a.event='profile_comment'
WHERE (u.id = a.sender_id OR u.id = a.receiver_id) and (u.id <> 379)
ORDER BY a.created_at DESC LIMIT 0, 10