3

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

4 Answers 4

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for great answer, and also giving info about "read", i have a problem, mysql_num_rows gives 0 even though i have "read = 0" in the database ?
1
SELECT COUNT(read), customer FROM msg WHERE read = 0 AND sent_to = '45' GROUP BY customer;

Comments

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

Comments

0

...

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.