小编典典

mysql条件连接取决于列

mysql

我正在尝试实现一个通用的通知系统。

notification_base:id,type,object
notificiation_sub:id,user_id,not_base_id,lastNotifyTime
notification_action:id,user_id,not_base_id,action,creationDate

因此,基本方案是,用户通过发布状态来创建通知基础项,或上传照片等(在这种情况下,照片是指notify_base表中的类型字段,而object_id是post_id或photo_id取决于类型)然后用户订阅为此通知基项目。(用户3订阅notification_base
5,最后通知时间x)

之后,另一个用户触摸此notification_base项。(例如,对状态发表评论或对照片进行评论)。此操作记录在notification_action表中(用户5在2011年2月2日做出“喜欢”操作)。

我想要的是如果上次notifiytime小于通知操作,则从用户订阅中获取notification_base项目,然后将它们与notification_action一起加入。

对于用户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具有“类型”和object_id

但我也想根据类型来连接object_id。因此,我可以实际了解所接触的对象。但是如您所见,type是动态的,如果type = post object
id引用了post表上的post_id,如果type = photo object 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;

我知道这是不正确的,就像伪代码


阅读 263

收藏
2020-05-17

共1个答案

小编典典

您不能有条件地在表之间创建联接。最好的方法是在陈述中使用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;
2020-05-17