有趣的选择mysql

时间:2013-04-13 14:40:46

标签: mysql

我有三个表 - 用户,城市和地区。

users - u_id, u_city
cities - c_id, r_c_id
regions - r_id, r_alias

userscities位于u_city = c_idcities以及regions占用r_c_id = r_id的位置。我有区域表的r_alias。是否可以计算我选择的区域中的用户数(我有r_alias)(COUNT(u_id))。

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

是的,有可能。

您需要先加入表格,

SELECT  a.r_alias, COUNT(*) AS TotalUser
FROM    regions a
        INNER JOIN cities b
            ON a.r_id = b.r_c_id
GROUP   BY a.r_alias

这将列出具有特定用户数的所有区域。如果要计算指定区域,只需添加WHERE子句。

SELECT  a.r_alias, COUNT(*) AS TotalUser
FROM    regions a
        INNER JOIN cities b
            ON a.r_id = b.r_c_id
WHERE   a.r_alias = 'valHERE'
GROUP   BY a.r_alias

答案 1 :(得分:1)

试试这个:

select count(u_id)
from users
join cities on u_city = c_id
join regions on r_c_id = r_id
where r_alias = "r_alias_value'

答案 2 :(得分:1)

附近执行select语句会更有效率
SELECT STRAIGHT_JOIN
  r.*,
  COUNT(u.u_id) AS `users`

FROM (
  SELECT * FROM regions
  WHERE r_alias LIKE '$region_alias'
) AS r

LEFT OUTER JOIN cities AS c ON (r.r_id = c.r_c_id)

LEFT OUTER JOIN users  AS u ON (u.u_city = c.c_id)

GROUP BY r.r_id;

因为它在加入其余表之前过滤到特定区域。

(代码在MySQL 5.6.10上测试)