Utku Dalmaz
Utku Dalmaz

Reputation: 10192

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

Upvotes: 3

Views: 115

Answers (4)

geeko
geeko

Reputation: 31

select count(sent_to), customer
from msg 
where read < 1
and sent_to = 45
group by customer

Upvotes: 1

Daniel Vassallo
Daniel Vassallo

Reputation: 344571

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)

Upvotes: 1

darcy
darcy

Reputation: 465

SELECT COUNT(read), customer FROM msg WHERE read = 0 AND sent_to = '45' GROUP BY customer;

Upvotes: 1

El Guapo
El Guapo

Reputation: 5781

...

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

Upvotes: 0

Related Questions