mysql conditional join depends on a column

后端 未结 1 484
逝去的感伤
逝去的感伤 2020-12-07 01:51

I\'m trying to implement a generic notification system.. I have a data structure like this;

notification_base:id,type,object
notificiation_sub:id,user_id,not         


        
相关标签:
1条回答
  • 2020-12-07 02:19

    you can't conditionally create joins across tables. The best way to do is to use LEFT JOIN and use you CASE in your SELECT statement. You must have specify common columns you want to show,

    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;
    
    0 讨论(0)
提交回复
热议问题