从多个表中选择带有计数的记录

时间:2015-03-23 20:10:53

标签: php mysql

我见过许多类似的帖子,但似乎无法将类似的案例与我的确切解决方案/需求配对。

我有6个表中的数据,需要从每个表中获取所有城市的列表以及每个城市的记录数量。

我当前的查询:

(SELECT res.CITY FROM rets_property_res res) 
UNION ALL 
(SELECT rnt.CITY FROM rets_property_rnt rnt) 
UNION ALL 
(SELECT lnd.CITY FROM rets_property_lnd lnd) 
UNION ALL 
(SELECT hir.CITY FROM rets_property_hir hir) 
UNION ALL 
(SELECT cnd.CITY FROM rets_property_cnd cnd) 
UNION ALL 
(SELECT mul.CITY FROM rets_property_mul mul) 
ORDER BY CITY ASC

我已经尝试了很多努力来添加计数但是无法正确使用语法,因为我对mySql语法不太了解。

3 个答案:

答案 0 :(得分:2)

(i)中。当您需要基于字段或字段的行数时,您可以在该字段上使用Group by

现在您想知道每个表的计数,因此您需要一个指定表名称的字段,如tName和...

通过这个,你将拥有每张桌子的城市数量

SELECT count(*) AS CNT, CITY, tName 
FROM (
    SELECT res.CITY ,'res' as tName 
    FROM rets_property_res res 
  UNION ALL 
    SELECT rnt.CITY,'rnt' as tName 
    FROM rets_property_rnt rnt
  UNION ALL 
    SELECT lnd.CITY,'lnd' as tName 
    FROM rets_property_lnd lnd
  UNION ALL 
    SELECT hir.CITY,'hir' as tName 
    FROM rets_property_hir hir
  UNION ALL
    SELECT cnd.CITY,'cnd' as tName 
    FROM rets_property_cnd cnd
  UNION ALL
    SELECT mul.CITY,'mul' as tName 
    FROM rets_property_mul mul
    ) as DT
Group by tName, CITY
ORDER BY CITY ASC

答案 1 :(得分:0)

如果您将整个查询放在子查询中,那么您可以从这些结果中计算出COUNT():

SELECT CITY, COUNT(*)
FROM (
  (SELECT res.CITY FROM rets_property_res res) 
  UNION ALL 
  (SELECT rnt.CITY FROM rets_property_rnt rnt) 
  UNION ALL 
  (SELECT lnd.CITY FROM rets_property_lnd lnd) 
  UNION ALL 
  (SELECT hir.CITY FROM rets_property_hir hir) 
  UNION ALL 
  (SELECT cnd.CITY FROM rets_property_cnd cnd) 
  UNION ALL 
  (SELECT mul.CITY FROM rets_property_mul mul) 
)
GROUP BY CITY

答案 2 :(得分:0)

试试这个,它将为您提供每个表中每个城市的计数

(SELECT res.CITY, resDup.res_count FROM rets_property_res res 
        JOIN (SELECT COUNT(CITY) res_count FROM rets_property_res GROUP BY CITY) resDup ON `resDup`.`CITY` = `res`.`CITY`
    ) 
    UNION ALL 
    (SELECT rnt.CITY, rntDup.rnt_count FROM rets_property_rnt rnt
        JOIN (SELECT COUNT(CITY) rnt_count FROM rets_property_rnt GROUP BY CITY) rntDup ON `rntDup`.`CITY` = `rnt`.`CITY`
    ) 
    UNION ALL 
    (SELECT lnd.CITY, lndDup.lnd_count FROM rets_property_lnd lnd
        JOIN (SELECT COUNT(CITY) lnd_count FROM rets_property_lnd GROUP BY CITY) lndDup ON `lndDup`.`CITY` = `lnd`.`CITY`
    ) 
    UNION ALL 
    (SELECT hir.CITY, hirDup.hir_count FROM rets_property_hir hir
        JOIN (SELECT COUNT(CITY) hir_count FROM rets_property_hir GROUP BY CITY) hirDup ON `hirDup`.`CITY` = `hir`.`CITY`
    ) 
    UNION ALL 
    (SELECT cnd.CITY, cndDup.cnd_count FROM rets_property_cnd cnd
        JOIN (SELECT COUNT(CITY) cnd_count FROM rets_property_cnd GROUP BY CITY) cndDup ON `cndDup`.`CITY` = `cnd`.`CITY`
    ) 
    UNION ALL 
    (SELECT mul.CITY, mulDup.mul_count FROM rets_property_mul mul
        JOIN (SELECT COUNT(CITY) mul_count FROM rets_property_mul GROUP BY CITY) mulDup ON `mulDup`.`CITY` = `mul`.`CITY`
    ) 
    ORDER BY CITY ASC

如果有任何问题,请告诉我