我需要编写一个查询来显示每个州的员工计数列表

时间:2015-07-14 23:05:37

标签: mysql

显示每个州的所有员工的计数。我写的查询是:

Select count(distinct a.id)   
from address a   
Group by a.state;

是否有更优化的解决方案?

有两个表

CREATE TABLE `address` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `city` varchar(255) NOT NULL,
  `state` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4832 DEFAULT CHARSET=utf8;

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fname` varchar(255) NOT NULL,
  `lname` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `title` varchar(255) NOT NULL,
  `dob` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=58993 DEFAULT CHARSET=utf8;

1 个答案:

答案 0 :(得分:1)

由于employeeaddress表之间没有关系,您的查询将无法生成正确的输出。

您应该在employee表中添加一个列,该列将引用id表中的address

ALTER TABLE employee
ADD COLUMN address_id INT NOT NULL;

然后,计算每个州的employee个数:

SELECT 
    a.state,
    COALESCE(COUNT(e.id), 0) AS employee_count
FROM address a
LEFT JOIN employee e
    ON e.address_id = a.id
GROUP BY a.state

此外,您可以添加FOREIGN KEY约束:

ALTER TABLE employee
ADD FOREIGN KEY fk_address(address_id)
REFERENCES address(id)
ON DELETE NO ACTION
ON UPDATE NO ACTION;