我正在尝试实现通用通知系统..我有这样的数据结构;
notification_base:id,type,object
notificiation_sub:id,user_id,not_base_id,lastNotifyTime
notification_action:id,user_id,not_base_id,action,creationDate
所以基本情况是,用户通过发布状态或上传照片等来创建通知基础项目。(在这种情况下,照片指的是notification_base表中的类型字段,object_id是post_id或photo_id取决于类型) 然后用户订阅此notification_base项目..(用户3订阅notification_base 5和最后通知时间x)
之后,另一个用户触摸此notification_base项。 (例如评论状态或照片) 此操作记录在notification_action表中(用户5在12/02/2011上执行'动作')..
我想要的是从用户订阅中获取notification_base项目,如果上一次通知时间小于通知操作,则通过notification_action加入它们。 我可以用这个sql继承它;
对于用户ID 3;
select * from notification_action
inner join notification_base on notification_action.not_base_id = notification_base.id
inner join notification_sub on notification_action.not_base_id = notification_sub.not_base_id
where notification_sub.user_id = 3 and notification_sub.lastShowDate < notification_action.creationDate ;
结果几乎是我想要的,例如
用户x对你的对象做了'动作',在时间t有'type'和object_id
但我也希望加入object_id取决于类型..所以我实际上可以学习触摸哪个对象..但是你可以看到类型是动态的,如果type = post对象id指的是post表上的post_id,如果type =照片对象id引用照片桌上的photo_id等。
我尝试这样做但得到一些语法错误;
SELECT *
FROM notification_action
INNER JOIN notification_base
ON notification_action.not_base_id = notification_base.id
INNER JOIN notification_sub
ON notification_action.not_base_id = notification_sub.not_base_id CASE notification_base.type
WHEN 'photo'
THEN (
INNER JOIN photo
ON photo.id = notification_base.object_id
)
ELSE (
INNER JOIN post
ON post.id = notification_base.object_id
)
END
WHERE notification_sub.user_id = 3
AND notification_sub.lastShowDate < notification_action.creationDate;
我知道这不正确,就像伪代码
答案 0 :(得分:6)
您无法有条件地跨表创建联接。最好的方法是使用LEFT JOIN
并在CASE
语句中使用SELECT
。您必须指定要显示的公共列,
SELECT *,
(CASE notification_base.type
WHEN 'photo'
THEN photo.columnName1
ELSE post.ColumnName1
END) as ColumnName1,
(CASE notification_base.type
WHEN 'photo'
THEN photo.columnName2
ELSE post.ColumnName2
END) as ColumnName2
FROM notification_action
INNER JOIN notification_base
ON notification_action.not_base_id = notification_base.id
INNER JOIN notification_sub
ON notification_action.not_base_id = notification_sub.not_base_id
INNER JOIN photo
ON photo.id = notification_base.object_id
INNER JOIN post
ON post.id = notification_base.object_id
WHERE notification_sub.user_id = 3
AND notification_sub.lastShowDate < notification_action.creationDate;