简体   繁体   中英

MySQL Count to rows as one

I have a database as laid out below.

mysql> select * from wants where itemname='lamp' order by location;
+------+--------------------+-------------+----------+----------+----------+
| sess | username           | room        | image    | item     | priority |
+------+--------------------+-------------+----------+----------+----------+
|   33 | user1@aol.com      | Family Room | DSC00649 | Lamp     |        1 |
|  235 | user2@yahoo.com    | Family Room | DSC00649 | Lamp     |        2 |
|   60 | user3@homtmail.com | Foyer       | DSC00527 | Lamp     |        1 |
|  197 | user4@gmail.com    | Foyer       | DSC00527 | Lamp     |        2 |
|  189 | user4@gmail.com    | Living Room | DSC00827 | Lamp     |        1 |
|  273 | user5@live.com     | Living Room | DSC00827 | Lamp     |        2 |
+------+--------------------+-------------+----------+----------+----------+
6 rows in set (0.00 sec)

What I am trying to do is get a count of each item per room.

When I run the query it should look like:

2 Family Room Lamp user1@aol.com user2@yahoo.com 
2 Foyer Lamp user3@homtmail.com user4@gmail.com
2 Living Room Lamp user4@gmail.com user5@live.com

Current Query:

$result1 = mysql_query("SELECT username, location, image, itemname, COUNT( itemname ) x  FROM wants GROUP BY itemname HAVING x >1 order by location ASC")

This will give the following output:

6 Family Room Lamp luser1@aol.com user2@yahoo.com user3@homtmail.com user4@gmail.com user4@gmail.com user5@live.com

I tried to use Concat to get the count of the first two rows but that did not help,

How can i break these out to get the rooms to read separately, when the Item name is the same?

You need to group by the room instead of the item. Also sounds like you're looking for group_concat to list the users:

select count(*), 
       room,
       group_concat(username)
from wants
where item ='lamp'
group by room

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