2010-04-21 93 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