我有一个如下所示的数据库。
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)
我想要做的是计算每个房间的每件物品。
当我运行查询时,它应该如下所示:
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
当前查询:
$result1 = mysql_query("SELECT username, location, image, itemname, COUNT( itemname ) x FROM wants GROUP BY itemname HAVING x >1 order by location ASC")
这将提供以下输出:
6 Family Room Lamp luser1@aol.com user2@yahoo.com user3@homtmail.com user4@gmail.com user4@gmail.com user5@live.com
我尝试使用Concat获取前两行的计数,但这没有帮助,
当项目名称相同时,我怎样才能打破这些房间以便单独阅读?
答案 0 :(得分:1)
您需要group by
房间而不是项目。听起来你正在寻找group_concat
列出用户:
select count(*),
room,
group_concat(username)
from wants
where item ='lamp'
group by room