我有两张桌子 - '提供'和'加入'。我需要从连接表中计算'provided_id'并在未找到时计为零。我的表格和输出要求如下。如何在mysql中使用单个查询来实现这一点?
TABLE : OFFERED
===============
offered_id data
----------- ----
1 aaaa
2 bbbb
3 cccc
4 dddd
5 eeee
6 ffff
TABLE : JOINED
===============
joined_id offered_id
----------- ----------
1 5
2 2
3 2
4 1
5 3
6 2
7 5
OUTPUT REQUIRED
===============
offered_id data count(offered_id) from joined table.(0 for no entry)
----------- ----- ------------------------------------------------
1 aaaa 1
2 bbbb 3
3 cccc 1
4 dddd 0
5 eeee 1
6 ffff 0
答案 0 :(得分:1)
使用count
:
SELECT OFFERED.OFFERED_id,OFFERED.data,(select count(JOINED.joined_id) FROM JOINED INNER JOIN OFFERED
ON JOINED.offered_id = OFFERED.offered_id) as count_joined FROM OFFERED
答案 1 :(得分:1)
尝试一下,它帮助我为我的项目实现同样的目标,它一定会帮助你。
import numpy as np
import pandas as pd
df = pd.read_csv("phased.txt")
match_counts = {(i,j):
np.sum(df[df.columns[i]] != df[df.columns[j]])
for i in range(3,len(df.columns))
for j in range(3,len(df.columns))}
match_counts
{(6, 4): 3,
(4, 7): 2,
(4, 4): 0,
(4, 3): 3,
(6, 6): 0,
(4, 5): 3,
(5, 4): 3,
(3, 5): 3,
(7, 7): 0,
(7, 5): 3,
(3, 7): 2,
(6, 5): 3,
(5, 5): 0,
(7, 4): 2,
(5, 3): 3,
(6, 7): 2,
(4, 6): 3,
(7, 6): 2,
(5, 7): 3,
(6, 3): 2,
(5, 6): 3,
(3, 6): 2,
(3, 3): 0,
(7, 3): 2,
(3, 4): 3}
答案 2 :(得分:0)
使用子查询可以实现...
SELECT OFFERED.offered_id, OFFERED.data, (SELECT COUNT(JOINED.joined_id) FROM JOINED WHERE JOINED.offered_id = OFFERED.offered_id) AS count_joined FROM OFFERED