0

我有三张表——用户、城市和地区。

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

由和由和由users和捆绑。我有区域表的 r_alias。是否可以计算我选择的那个地区的用户(我有 r_alias)()。citiesu_city = c_idcitiesregionsr_c_id = r_idCOUNT(u_id)

谢谢你的帮助!

4

3 回答 3

1

在附近执行选择语句会更有效

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 上测试过)

于 2013-04-13T15:38:33.310 回答
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
于 2013-04-13T14:45:48.193 回答
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'
于 2013-04-13T14:46:48.897 回答