我在select 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
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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 ;
见这里.. link
答案 4 :(得分:-2)
SELECT LocationChosen, Count(*) FROM usersTable GROUP BY LocationChosen