我有两张桌子"用户"和"收件人" 。现在我想在这个办公室展示所有办公室和总收件人。但我的查询返回哪些办公室有计数。但我需要显示所有办公室和计数。
喜欢:
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
"
结构:
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;
答案 0 :(得分:1)
即使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;