如何在不同加入MySQL的情况下COUNT条件?

时间:2017-01-12 17:44:58

标签: mysql

我有两张桌子:

mysql> DESCRIBE swaps;
+-------------+----------+------+-----+---------+----------------+
| Field       | Type     | Null | Key | Default | Extra          |
+-------------+----------+------+-----+---------+----------------+
| id          | int(11)  | NO   | PRI | NULL    | auto_increment |
| user1_id    | int(11)  | NO   |     | NULL    |                |
| user2_id    | int(11)  | NO   |     | NULL    |                |
| hasto       | int(11)  | NO   |     | NULL    |                |
| requested   | datetime | NO   |     | NULL    |                |
| accepted    | datetime | YES  |     | NULL    |                |
| swapped1    | datetime | YES  |     | NULL    |                |
| swapped2    | datetime | YES  |     | NULL    |                |
| rejected    | datetime | YES  |     | NULL    |                |
| rejected_by | int(11)  | YES  |     | NULL    |                |
+-------------+----------+------+-----+---------+----------------+
mysql> DESCRIBE messages;
+-----------+----------+------+-----+-------------------+----------------+
| Field     | Type     | Null | Key | Default           | Extra          |
+-----------+----------+------+-----+-------------------+----------------+
| msg_id    | int(11)  | NO   | PRI | NULL              | auto_increment |
| sender_id | int(11)  | NO   |     | NULL              |                |
| msg       | text     | NO   |     | NULL              |                |
| msg_time  | datetime | NO   |     | CURRENT_TIMESTAMP |                |
| swap_id   | int(11)  | NO   |     | NULL              |                |
| seen      | datetime | YES  |     | NULL              |                |
+-----------+----------+------+-----+-------------------+----------------+

并查询我从this问题调整

SELECT s.*, m.*
FROM swaps as s
JOIN messages as m
ON (s.id= m.swap_id AND m.msg_time=
  (SELECT MAX(msg_time) FROM messages WHERE messages.swap_id = s.id));

因此,我为每个交换单行,以及有关此交换中最后发送的消息的信息。我想添加没有看到过的消息计数(m.seen IS NULL)。

我尝试了不同的方法但总是出错。我想要的是在相应的交换中添加消息计数,并在我的结果集中看到IS NULL。将不胜感激任何建议。

1 个答案:

答案 0 :(得分:0)

您可以将计数添加为子查询:

SELECT s.*, m.*,
       (SELECT COUNT(*) FROM messages m2 WHERE m2.seen IS NULL) as seen_is_null
FROM swaps s JOIN
     messages m
     ON s.id= m.swap_id AND
        m.msg_time =(SELECT MAX(m2.msg_time) FROM messages m2 WHERE m2.swap_id = s.id));

计算所有消息似乎很奇怪,但这就是问题所要求的。当然,您可以引入一个相关子句来计算给定的交换或其他内容。