Mysql Postgresql上的查询联接和计数
我使用Postgresql。我有这样的a&b桌Mysql Postgresql上的查询联接和计数,mysql,sql,postgresql,join,left-join,Mysql,Sql,Postgresql,Join,Left Join,我使用Postgresql。我有这样的a&b桌 a_table +--------+---------------+ | id | free_value | +--------+---------------+ | 1 | 3 | | 2 | 2 | | 3 | 1 | | 4 | 3 | | 5 | 2 | |
a_table
+--------+---------------+
| id | free_value |
+--------+---------------+
| 1 | 3 |
| 2 | 2 |
| 3 | 1 |
| 4 | 3 |
| 5 | 2 |
| 6 | 8 |
| 7 | 4 |
+--------+---------------+
b_table
+--------+---------------+
| id | a_table_id |
+--------+---------------+
| 1 | 2 |
| 2 | 2 |
| 3 | 6 |
| 4 | 5 |
| 5 | 3 |
| 6 | 3 |
+--------+---------------+
我可以在b_表上为无计数的_值编写查询,并描述这样的计数吗
count_free_value_table
+----------------+-----------+
| free_value | count |
+----------------+-----------+
| 2 | 3 |
| 1 | 2 |
| 8 | 1 |
| 3 | 0 |
| 4 | 0 |
+----------------+-----------+
我尝试使用
选择free\u值,从一个\u表左键连接一个\u表上的b\u表。id=b\u表。a\u表\u id
但它不起作用
谢谢你的帮助。我对此很傻。试试COUNT(b_table.id)
COUNT
统计遇到的所有非空值,这就是为什么(我猜)对于不匹配的自由_值,您会得到1;因为不匹配的值在其行中仍有自己的值
编辑:另外,are的评论和Alim的回答也是正确的,因为您需要按自由值分组。否则,您将获得联接的总行数,并有效地随机选择一个free\u值
试试看
SELECT free_value, count(free_value)
from a_table LEFT JOIN b_table ON a_table.id = b_table.a_table_id
group by free_value
尝试此查询。从a_表左侧选择自由值,count(*)在a_表上加入b_表。id=b_表。a_表id按自由值分组
计数自由值
将导致没有引用的值为1。我将count(自由值)更改为count(b_表.id),它也可以正常工作,感谢@uuerdo。谢谢你的帮助。
SELECT free_value, count( b_table.id ) count
FROM a_table
LEFT JOIN b_table ON a_table.id = b_table.a_table_id
GROUP BY free_value
ORDER BY count DESC