在多个表中使用count和join

时间:2016-07-08 15:48:10

标签: mysql

实施例: 表1:

import dbus
session_bus = dbus.SessionBus()
purple_obj = session_bus.get_object("im.pidgin.purple.PurpleService","/im/pidgin/purple/PurpleObject")
purple_int = dbus.Interface(purple_obj, "im.pidgin.purple.PurpleInterface")

user = "here i put the people, but i need the main room"

my_account_id = purple_int.PurpleAccountsGetAllActive()[0]
conv = purple_int.PurpleConversationNew(1, my_account_id, user)
conv_im = purple_int.PurpleConvIm(conv)
purple_int.PurpleConvImSend(conv_im, "the message.......")

表2

id   name

1    sim
2    sam
3    jas

表3:

key   age
1     10
1     20
2     40
3     10

现在,我需要的是

在两个表中使用group by分组的行数,即表A和表B.

id    rating
2       7
2       6
3       8
3       7
1       9

结果我期待:

select t1.id, count(t2.key) as a, count(t3.id) as b
FROM 
table1 t1
LEFT JOIN 
table2 t2
ON 
t1.id = t2.key
LEFT JOIN 
table3 t3
ON 
t1.id = t3.id
GROUP BY t1.key, t2.id

1 个答案:

答案 0 :(得分:1)

您正在获得重复项,因为您在所有3个表之间创建了交叉产品。使用COUNT(DISTINCT)过滤掉重复项。

select t1.id, count(DISTINCT t2.age) as a, count(DISTINCT t3.rating) as b
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.key
LEFT JOIN table3 t3 ON t1.id = t3.id
GROUP BY t1.id