2010-04-21 90 views
3

这里是mysql的容易MySQL查询问题

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

回答

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

感谢您的很好的回答,也给予关于“读”的信息,我有一个问题,mysql_num_rows给出0,即使我有“读= 0”在数据库中? – 2010-04-21 17:36:08

+0

哦好吧我修好了thx – 2010-04-21 17:38:08

0

...

select count(*), customer from msg where read = 0 group by customer 
+0

和'sent_to'想必?最确定的是 – 2010-04-21 17:22:48

+0

! – 2010-04-22 00:11:19

1
SELECT COUNT(read), customer FROM msg WHERE read = 0 AND sent_to = '45' GROUP BY customer; 
1
select count(sent_to), customer 
from msg 
where read < 1 
and sent_to = 45 
group by customer