Mysql 根据主表中列的值联接表
我想根据列类型的值连接不同的表。 这是我当前的伪代码:Mysql 根据主表中列的值联接表,mysql,join,Mysql,Join,我想根据列类型的值连接不同的表。 这是我当前的伪代码: notificationTable ID type typeID userID ============================================== 1 comment 34 2 2 accept 22 2 eventTable ID
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
但我强烈建议重新设计您的系统,以避免多态关系…这可以通过mysql中的过程实现,也可以通过编码实现。老实说,我建议您甚至不要尝试去弄清楚这一点。听起来你应该专注于改变桌子的布局结构。你想要的结果是什么?
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