我有2个表,“联系人组”和“联系人”订户,我们正在尝试联接和计数类似的值。对于没有任何值的对应字段,我需要一个值“ 0”。表格示例如下:
Contact Group Table:
id | name | Hash |
1 | January | asld |
2 | February | asld |
3 | March | asld |
4 | April | asld |
5 | May | asld |
Contact Subscriber Table:
id | name | group_id | subscribed at | unsubscribed at |
1 | Luke Skywalker | 1 | 20190211 | NULL |
1 | Darth Vader | 2 | 20190211 | NULL |
1 | Tony Stark | 1 | 20190211 | NULL |
1 | Bruce Wayne | 3 | 20190211 | NULL |
1 | Connor MacLeod | 5 | 20190211 | NULL |
联系人组表中的“ id”字段与联系人订户表中的“ group_id”字段匹配。
使用上面的示例,我们正在寻找以下输出:
id | name | Value
1 | January | 2
2 | February | 1
3 | March | 1
4 | April | 0
5 | May | 1
我觉得我们接近了,我们能够提供下面显示的以下代码,该代码显示了ID和月份,但我们无法使count函数正常工作。这是我们目前拥有的:
SELECT
contact_group.id,
contact_group.name,
COALESCE(group_id, 0) AS value FROM
contact_group
LEFT JOIN
contact_subscriber ON contact_group.id = contact_subscriber.group_id;
这提供了以下结果:
+----+---------------+-------+
| id | name | value |
+----+---------------+-------+
| 1 | January | 1 |
| 1 | January | 1 |
| 2 | February | 2 |
| 3 | March | 3 |
| 4 | April | 0 |
| 5 | May | 5 |
+----+---------------+-------+
6 rows in set (0.00 sec)
在此方面的任何帮助将不胜感激,我一直在努力寻找解决办法,大约一个星期。
答案 0 :(得分:0)
使用聚合函数count()
SELECT
contact_group.id
contact_group.name,
count(contact_subscriber.group_id) AS value FROM
contact_group
LEFT JOIN
contact_subscriber ON contact_group.id = contact_subscriber.group_id
group by contact_group.name, contact_group.id
答案 1 :(得分:0)
SELECT
contact_group.id, contact_group.name, COUNT(contact_subscriber.id) AS value
FROM contact_group
LEFT JOIN contact_subscriber ON contact_group.id = contact_subscriber.group_id
GROUP BY contact_group.id, contact_group.name
答案 2 :(得分:0)
一种方法使用子查询:
SELECT cg.*,
(SELECT COUNT(*)
FROM contact_subscriber cs
WHERE cg.id = cs.group_id
) as value
FROM contact_group cg;
因为这可以利用contact_subscriber(group_id)
上的索引,所以它可能比其他方法(特别是外部查询中使用GROUP BY
的方法)要快得多。