MySQL查询:合并三个表中的行并输出为一个

时间:2011-06-20 21:05:08

标签: mysql sql

我想从三个表中提取信息,这些表由某些ID相互链接。你能告诉我我该怎么做。我试过但是三张桌子太复杂了。这是我想要做的:

Here are the three tables and resulting table

所以基本上从上面三个表中我想要将USER与各自的PID匹配,显示仅特定SPEC类型的计数,例如示例中所示的ROUND。 (也可能发生同样的PID被分配给两个不同的用户,例如PID = 1,用户AAA和BBB)。

你能告诉我怎么去吗?

3 个答案:

答案 0 :(得分:1)

SELECT 
  t1.USER, 
  t1.PID, 
  COUNT(T3.SPEC) AS CountRound
FROM Table1 t1
  LEFT JOIN Table2 t2 ON t1.PID = t2.PID 
  LEFT JOIN Table3 t3 ON t2.LID = t3.LID AND t3.SPEC = 'ROUND'
GROUP BY
  t1.USER,
  t1.PID

答案 1 :(得分:0)

开始的东西?

SELECT 
 T1.USER, 
 T1.PID, 
 IFNULL(COUNT(T3.SPEC), 0) 
FROM 
 Table1 T1 LEFT JOIN Table2 T2 
  ON T1.PID = T2.PID 
 JOIN Table3 T3 
  ON T2.LID = T3.LID 
WHERE T3.SPEC = 'ROUND'

答案 2 :(得分:0)

    select user,pid,count(*) from (

    select table1.user,table1.pid,table3.spec 
    from 
      table1,
      table2,
      table3 
    where 
      table1.pid=table2.pid(+) 
    and table2.lid=table3.lie(+) 
    and table3.spec='Round' 

) 
group by user,pid