MySQL帮助清理总计数

时间:2014-03-03 16:21:20

标签: mysql sql

JOIN语句出现问题。

我正在尝试获取每个名称的总数,而不是当前的1和其他相同名称的记录

SELECT a.`name`, 
    (SELECT COUNT(b.`id`) 
    FROM `host1_hosting` AS b 
    WHERE b.`id` = c.`host1_servers_host1_hosting_1host1_hosting_idb`) AS HostingCount
FROM `host1_servers` AS a
LEFT JOIN `host1_servers_host1_hosting_1_c` AS c ON c.`host1_servers_host1_hosting_1host1_servers_ida` = a.`id`
ORDER BY a.`name`

返回示例

名称HostingCount

姓名1

姓名1

姓名1

它应该在哪里:

姓名3

我确信这很简单,但是星期一早上,我有雾了

查询2

SELECT a.`name`, COUNT(d.`id`)
FROM `host1_servers` AS a
JOIN `host1_servers_host1_hosting_1_c` AS c ON c.`host1_servers_host1_hosting_1host1_servers_ida` = a.`id`
JOIN `host1_hosting` AS d ON d.`id` = c.`host1_servers_host1_hosting_1host1_hosting_idb`
ORDER BY a.`name`

获取1条姓名记录,但总共有COUNT

1 个答案:

答案 0 :(得分:1)

您的第二个查询需要group by

SELECT a.`name`, COUNT(d.`id`)
FROM `host1_servers` AS a
JOIN `host1_servers_host1_hosting_1_c` AS c ON c.`host1_servers_host1_hosting_1host1_servers_ida` = a.`id`
JOIN `host1_hosting` AS d ON d.`id` = c.`host1_servers_host1_hosting_1host1_hosting_idb`
GROUP BY a.name
ORDER BY a.`name`;

如果没有GROUP BY,MySQL会将查询解释为聚合查询以生成一行。 count()是整体计数。列name是从其中一行中任意选择的(使用不能在任何其他数据库中使用的MySQL扩展名)。

编辑:

如果要保留第一个表中的所有名称并进行计数,请使用left outer join

SELECT a.`name`, COUNT(d.`id`)
FROM `host1_servers` a LEFT OUTER JOIN
     `host1_servers_host1_hosting_1_c` c
     ON c.`host1_servers_host1_hosting_1host1_servers_ida` = a.`id` LEFT OUTER JOIN
    `host1_hosting` d
     ON d.`id` = c.`host1_servers_host1_hosting_1host1_hosting_idb`
GROUP BY a.name
ORDER BY a.`name`;