使用count加入/合并3个表

时间:2014-04-24 00:01:19

标签: sql sqlite join merge

我有3张桌子:

人:

pid    name
1      Cal
2      Example
3      Another
4      Person

talkingPoints:

tid    pid    talkingPoint
1      1      "..."
2      1      "..."
3      2      "..."

事实:

fid    pid    fact
1      3      "..."
2      2      "..."

我试图将一些会话点和事实与“人”结合起来,例如:

pid    name     talkingPoints  facts
1      Cal      2              null
2      Example  1              1
3      Another  null           1
4      Person   null           null

(按talkPoints desc排序,然后按字母顺序排列,包括'人行'行没有任何计数值)

我成功地将人们和#39;只有一张桌子:

SELECT a.pid,a.name,
count(b.tid)  
FROM people a, talkingPoints b  
WHERE a.pid=b.pid  
GROUP BY b.pid;

但该查询会忽略零计数的行(例如,行' Person')

我修改了这个查询,该查询可以正常使用“talkPoints'但我无法使其适应并结合事实'就像我上面的示例表一样。

select people.pid, people.name, x.talkingPoints from people left join 
(select pid, name, count(name) talkingPoints from 
(select people.pid, people.name from people
join talkingPoints on talkingPoints.pid = people.pid)
 as talkingPoints group by talkingPoints.pid)
 as x on x.pid = people.pid order by talkingPoints desc, people.name asc;

(可能是一种可怕的方式,但同时也有效)

如何调整查询以便输出像我的示例一样的表?

2 个答案:

答案 0 :(得分:1)

SELECT  a.pid,
        a.name,
        COUNT(DISTINCT b.tid) talkingpoints,
        COUNT(DISTINCT c.fid) facts
FROM    people a
        LEFT JOIN talkingPoints b
            ON a.pid = b.pid
        LEFT JOIN facts c
            ON a.pid = c.pid
GROUP   BY a.pid, a.name
ORDER   BY a.pid

答案 1 :(得分:0)

在SELECT子句中使用独立的相关子查询可以避免由连接引起的重复:

SELECT pid,
       name,
       (SELECT COUNT(*)
        FROM talkingPoints
        WHERE pid = people.pid) AS talkingPoints,
       (SELECT COUNT(*)
        FROM facts
        WHERE pid = people.pid) AS facts
FROM people

SQLFiddle