mysql - 当没有可用值时,如何使用 mysql 查询显示空字段?

标签 mysql

我有两个表“用户”和“收件人”。现在我想显示该办公室的所有办公室和收件人总数。但我的查询返回哪些办公室有计数。但我需要显示所有办公室和计数。

喜欢:

id          office_name           count
========================================
1             Dhaka                0
2             Chittagong           2

当前查询:“

SELECT users.id as office_id, users.office_name , count(recipient.id) as total_count 
FROM users 
right outer JOIN recipient on recipient.office_id = users.id
WHERE ( users.del_status = 0 and users.type='agency')
order by users.id

"

用户表: enter image description here

收件人表: enter image description here

结构:

CREATE TABLE `recipient` (
  `id` int(10) NOT NULL,
  `name` varchar(100) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `mobile` varchar(15) NOT NULL,
  `age` int(10) NOT NULL,
  `reg_no` varchar(10) NOT NULL,
  `address` varchar(255) NOT NULL,
  `disability_type` int(10) NOT NULL,
  `education` varchar(255) NOT NULL,
  `office_id` int(10) NOT NULL,
  `del_status` tinyint(1) NOT NULL,
  `create_date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;      

 CREATE TABLE `users` (
  `id` tinyint(4) NOT NULL,
  `office_name` varchar(255) DEFAULT NULL,
  `district_id` int(10) DEFAULT NULL,
  `upazilla_id` int(10) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  `mobile` varchar(11) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(100) NOT NULL,
  `type` varchar(10) NOT NULL,
  `del_status` tinyint(1) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

最佳答案

您可以使用LEFT JOIN获取所有办公室,即使它们在recipient表中没有条目,例如:

SELECT u.id, u.office_name, COUNT(r.id) AS `count`
FROM users u LEFT JOIN recipient r ON u.id = r.office_id
GROUP BY u.id, u.office_name;

关于mysql - 当没有可用值时,如何使用 mysql 查询显示空字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44789984/

相关文章:

php - Mysql PDO 中 "RETURNING"子句的语法

mysql - 关于社交网络帖子的表格创建

mysql - Laravel 迁移值从 null 到 string

mysql根据日期查询

php - MYSQL 搜索 - PHP 表单

php+socket.io+mysql - 像聊天一样的 Messenger

php - 注册表: No error showing but No data on mysql DATABASE

php - 如果用户已经提交页面,则显示错误消息,然后重定向到引用页面

mysql - Mysql(innodb)行级锁定是解决方案吗?

MySQL:返回一个表中以另一个表为条件的值列表