1

我正在为我的社交网络应用程序制作通知方案。我有不同类型的通知,分为两组:朋友相关和事件相关。目前,我的数据库架构是这样的:

+---------------------+------------------------+------+-----+---------+----------------+
| 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    |                |
+---------------------+------------------------+------+-----+---------+----------------+

现在,我有两个不同的表格,分别是事件相关通知和朋友相关通知。以下是事件相关通知表的架构:

+-------------------------+----------------------------------------------------+------+-----+---------+-------+
| 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,通知类型,我还有 4 个表格info-edited,因为每个表格都需要具有不同类型的属性(例如,kicked需要一个原因)。

现在,我想编写一个条件 SQL 查询,使其notificationevent_notificationif不同。notification_typeevent

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 .....

会有这么多的内部连接有没有更好的方法呢?我认为我的查询也不是很优化,如果可以提供任何帮助,将不胜感激。

4

1 回答 1

1

您可以使用连接。但是,您希望使用左外连接而不是内连接来创建查询:

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 ...

不要担心连接的扩散。如果您的表具有适当的索引,它们将执行良好。

请考虑更改数据结构,以便您只有一张表用于不同的通知类型。有几个未使用的字段不会增加太多的性能开销,尤其是当您考虑拥有如此多的连接的复杂性以及拥有更多表的额外管理开销时。

于 2013-04-19T20:55:27.170 回答