gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:44:50 28 4
gpt4 key购买 nike

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

喜欢:

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com