这是mysql上的“msg”表
sent_to customer msg read
------- -------- ------ -----
45 3 bla 0
34 4 bla 1
34 6 bla 0
45 3 bla 0
56 7 bla 1
45 8 bla 0
例如id为45登录的用户,
我希望他看到这个,
you have 2 unread msg to your "number 3" customer
you have 1 unread msg to your "number 8" customer
就像新闻提要
我应该使用什么查询?
THX
答案 0 :(得分:1)
您可能需要使用以下查询。
SELECT CONCAT('You have ',
COUNT(`read`),
' unread msg to your number ',
customer,
' customer') AS news
FROM msg
WHERE `read` = '0' AND `sent_to` = '45'
GROUP BY customer;
请注意,read
是MySQL中的保留字,因此您必须将其括在反引号中。 (Source)
测试用例:
CREATE TABLE msg (
`sent_to` int,
`customer` int,
`msg` varchar(10),
`read` int
);
INSERT INTO msg VALUES(45, 3, 'bla', 0);
INSERT INTO msg VALUES(34, 4, 'bla', 1);
INSERT INTO msg VALUES(34, 6, 'bla', 0);
INSERT INTO msg VALUES(45, 3, 'bla', 0);
INSERT INTO msg VALUES(56, 7, 'bla', 1);
INSERT INTO msg VALUES(45, 8, 'bla', 0);
查询结果:
+-------------------------------------------------+
| news |
+-------------------------------------------------+
| You have 2 unread msg to your number 3 customer |
| You have 1 unread msg to your number 8 customer |
+-------------------------------------------------+
2 rows in set (0.00 sec)
答案 1 :(得分:1)
SELECT COUNT(read), customer FROM msg WHERE read = 0 AND sent_to = '45' GROUP BY customer;
答案 2 :(得分:1)
select count(sent_to), customer
from msg
where read < 1
and sent_to = 45
group by customer
答案 3 :(得分:0)
...
select count(*), customer from msg where read = 0 group by customer