mysql - 查找每个办公室的员 worker 数 - Mysql

标签 mysql sql database

我试图显示每个办公室有多少名员工以及办公室名称,但我无法让它工作。我已经尝试过这个

select count(*) as count,office_staff.staff_id
from staff
inner join office_staff on staff.staff_id = office_staff.staff_id
group by staff.staff_id 

但我得到的输出是这样的:

# count, staff_id
'1', '1001'
'1', '1002'
'1', '1003'
'1', '1004'
'1', '1005'
'1', '1006'

表格

-- -----------------------------------------------------
-- Table `mydb`.`staff`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`staff` (
  `staff_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `office_id` INT(10) UNSIGNED NOT NULL,



-- -----------------------------------------------------
-- Table `mydb`.`office_staff`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`office_staff` (
  `office_staff_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `staff_id` INT(10) UNSIGNED NOT NULL,
  `office_id` INT(10) UNSIGNED NOT NULL,
  `


-- -----------------------------------------------------
-- Table `mydb`.`offices`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`offices` (
  `office_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `address_id` INT(10) UNSIGNED NOT NULL,

有人可以帮我吗?谢谢!

最佳答案

我假设您的 offices 表中有一个名为 Name 的列(您的结构被切断)。我提取 Name 的原因是因为这一行:

I am trying to display how many staffs work in each office along with the offices name

这应该是您需要做的全部事情(根据需要更改列名称):

Select  O.Name   As OfficeName,
        Count(*) As count
From    staff        S
Join    office_staff OS On S.staff_id = OS.staff_id
Join    office       O  On O.Office_Id = OS.Office_Id
Group By O.Name

关于mysql - 查找每个办公室的员 worker 数 - Mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41643083/

相关文章:

php - JOIN sql 语句的问题

sql - 如果 condition1 为真,则将一个表与一个表连接,如果条件 1 为假,则与另一个表连接?

php - 在 PHP 和 MySQL 中使用 ENUM 指定用户或管理 session

database - 如何使用数据库中的汉字?

mysql - 日期数据类型的 fatal error : MySQL Insert from VB.

database - 自动调整 levelDB 磁盘空间?

php - 如何禁用 magento 在线销售功能?

mysql - 在ejabberd中配置mysql连接

php - 将 MySQL 获取数组存储在变量中是否只使用一次?

mysql - 基于标志的SQL查询