简体   繁体   中英

easy mysql query question

here is the "msg" table on 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

for example user whose id number is 45 logs in,

i want him to see this,

you have 2 unread msg to your "number 3" customer
you have 1 unread msg to your "number 8" customer

like a news feed

what query should i use for this ?

thx

You may want to use the following query.

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;

Note that read is a reserved word in MySQL, so you have to enclose it in backticks. ( Source )

Test case:

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);

Query result:

+-------------------------------------------------+
| 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)
SELECT COUNT(read), customer FROM msg WHERE read = 0 AND sent_to = '45' GROUP BY customer;
select count(sent_to), customer
from msg 
where read < 1
and sent_to = 45
group by customer

...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM