根据主表中列的值连接表

时间:2013-01-04 17:58:29

标签: mysql join

notificationTable
ID              type        typeID      userID
==============================================
1               comment     34          2
2               accept      22          2

eventTable
ID              event       content
===================================
21              post        34  
22              accept      22

commentTable
ID              comment     eventID
===================================
34              'test'      21

我想根据列类型的值加入不同的表。 这是我目前的伪代码:

SELECT *
FROM notificationTable notification
IF (notification.type == 'comment')
    LEFT JOIN commentTable comment
    ON notification.typeID = comment.ID
ELSEIF (notification.type == 'accept')
    LEFT JOIN evenTable event
    ON notification.typeID = event.ID
WHERE notification.userID = 2

任何人都知道我的意图的真实问题?

1 个答案:

答案 0 :(得分:2)

这样的东西
SELECT *
FROM notificationTable notification   
LEFT JOIN commentTable comment
ON (notification.typeID = comment.ID AND notification.type == 'comment')
LEFT JOIN evenTable event
ON (notification.typeID = event.ID AND notification.type == 'accept')
WHERE notification.userID = 2

但我强烈建议您重新设计系统以避免多态关系...