【问题标题】:Join table depending on value of column in main table根据主表中列的值连接表
【发布时间】:2013-01-04 17:58:28
【问题描述】:
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 中的过程实现,也可以通过编码来实现
  • 老实说,我建议不要试图弄清楚这一点。听起来您应该专注于更改表格的布局结构。
  • 你想要的结果是什么?

标签: mysql join


【解决方案1】:

有点像

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多