我正在为我的社交网络应用制定一个通知方案。我有不同类型的通知,分为两组:与 friend 相关的和与事件相关的。目前,我的数据库架构是这样的:
+---------------------+------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+------------------------+------+-----+---------+----------------+
| notification_id | int(11) | NO | PRI | NULL | auto_increment |
| notification_type | enum('event','friend') | NO | | NULL | |
| notification_date | datetime | NO | | NULL | |
| notification_viewed | bit(1) | NO | | NULL | |
| user_id | int(11) | NO | MUL | NULL | |
+---------------------+------------------------+------+-----+---------+----------------+
现在,我有两个不同的表,用于事件相关通知和 friend 相关通知。以下是事件相关通知表的架构:
+-------------------------+----------------------------------------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------------------+----------------------------------------------------+------+-----+---------+-------+
| notification_id | int(11) | NO | PRI | NULL | |
| event_id | int(11) | NO | MUL | NULL | |
| event_notification_type | enum('added','kicked','new-message','info-edited') | NO | | NULL | |
+-------------------------+----------------------------------------------------+------+-----+---------+-------+
我又为每个 kicked
、added
、new-message
、info-edited
添加了 4 个表code> 类型的通知,因为每个都需要具有不同类型的属性(例如 kicked
需要一个原因)。
现在,我想编写一个条件 SQL 查询,以便在 notification_type
为 event< 时将
否则不同。 notification
与 event_notification
连接起来
SELECT * FROM notification_table t WHERE t.seen = FALSE AND t.user_id = ? INNER JOIN event_notification en ON(t.notification_type='event' AND en.notification_id = t.notification_id) INNER JOIN .....
将有这么多内连接,有没有更好的方法呢?我认为我的查询也不是很优化,如果能提供任何帮助,我将不胜感激。
最佳答案
您可以使用连接。但是,您想使用左外连接而不是内连接来创建查询:
SELECT *
FROM notification_table t
WHERE t.seen = FALSE AND t.user_id = ? left JOIN
event_notification en
ON(t.notification_type='event' AND en.notification_id = t.notification_id) left JOIN ...
不必担心联接的激增。如果您的表有适当的索引,它们将运行良好。
请考虑更改数据结构,以便您只有一个表用于不同的通知类型。有一些未使用的字段不会增加太多性能开销,尤其是当您考虑到拥有如此多的联接的复杂性以及拥有更多表的额外管理开销时。
关于php - MySQL 中使用 IF-ELSE 的条件连接语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16112850/