查询 JOIN 和 Count ON Postgresql
Query JOIN And Count ON Postgresql
我使用 Postgresql。我有一个 & b table 这样的
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_table 上为计数 free_value 编写查询并像这样计数吗?
count_free_value_table
+----------------+-----------+
| free_value | count |
+----------------+-----------+
| 2 | 3 |
| 1 | 2 |
| 8 | 1 |
| 3 | 0 |
| 4 | 0 |
+----------------+-----------+
我试过 SELECT free_value, count(free_value) from a_table LEFT JOIN b_table ON a_table.id = b_table.a_table_id
但是不行。
感谢您的帮助。我傻了。
试试COUNT(b_table.id)
; COUNT
计算遇到的所有非空值,这就是为什么(我猜)你得到 1 不匹配的 free_values
;因为不匹配的值在它们的行中仍然有它们自己的值。
编辑:此外,are 的评论和 Alim 的回答也是正确的,因为您需要 group by free_value
。 否则,您将获得 JOIN 的总行数,以及有效随机选择的 free_value
.
尝试
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
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
试试这个查询。
我使用 Postgresql。我有一个 & b table 这样的
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_table 上为计数 free_value 编写查询并像这样计数吗?
count_free_value_table
+----------------+-----------+
| free_value | count |
+----------------+-----------+
| 2 | 3 |
| 1 | 2 |
| 8 | 1 |
| 3 | 0 |
| 4 | 0 |
+----------------+-----------+
我试过 SELECT free_value, count(free_value) from a_table LEFT JOIN b_table ON a_table.id = b_table.a_table_id
但是不行。
感谢您的帮助。我傻了。
试试COUNT(b_table.id)
; COUNT
计算遇到的所有非空值,这就是为什么(我猜)你得到 1 不匹配的 free_values
;因为不匹配的值在它们的行中仍然有它们自己的值。
编辑:此外,are 的评论和 Alim 的回答也是正确的,因为您需要 group by free_value
。 否则,您将获得 JOIN 的总行数,以及有效随机选择的 free_value
.
尝试
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
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
试试这个查询。