0

我在选择 sql 语句中需要帮助。

在我的 mysql 数据库中:

位置表

serialID(AI)|locations | telephone | address
---------------------------------------------
1           | A       
2           | B
3           | C
4           | D

users table
userID | location chosen
-------------------------
1      | A
2      | B
3      | B

我想统计选择特定位置并显示在表格中的人数。因此,如果该特定位置有更多用户选择作为他们最喜欢的位置,它将向上移动到第一行。我可以知道我该怎么做吗?

当它填充到动态表中时是这样的 - >

location | address | telephone | user's favourable
B        |  -      | -         |  2
A        |  -      | -         |  1
C        |  -      | -         |  0
D        |   -     | -         |  0
4

5 回答 5

1

你可以做这样的查询:

SELECT l.locations, l.telephone, l.address, COUNT (u.userID) as `location_count`
FROM location AS l
LEFT OUTER JOIN users AS u on l.locations = u.location_chosen
GROUP BY l.locations
ORDER BY `location_count` DESC
于 2013-01-15T16:20:57.817 回答
0
SELECT  loc.*, countResult.usersFavourable
FROM    location loc
        LEFT JOIN
        (
            SELECT  locationChoosen, COUNT(*) `usersFavourable`
            FROM    users
            GROUP BY    locationChoosen
        ) countResult ON loc.locations = countResult.locationChoosen
ORDER BY countResult.usersFavourable DESC, loc.locations
于 2013-01-15T16:20:37.577 回答
0

尝试这样的事情:

SELECT  l.location, l.address, l.telephone, COUNT(u.userID) AS [users favourable]
FROM    location l
        LEFT JOIN
            users u
            ON l.location = u.locationchosen
GROUP BY l.location, l.address, l.telephone
于 2013-01-15T16:20:43.793 回答
0

用这个:

select count(userId) count,locations,address,telephone 
from Table1 Left join Table2 
on Table1.locations = Table2.location

group by locations order by count desc ;

看这里..链接

于 2013-01-15T16:35:07.757 回答
-2
 SELECT LocationChosen, Count(*) FROM usersTable GROUP BY LocationChosen
于 2013-01-15T16:20:12.600 回答