计算2个表的相等字段和第3个内部连接

时间:2016-03-12 03:56:57

标签: mysql sql inner-join

我有3张桌子

Table cases: docket is pk 
| docket |   dt_file  |
-----------------------
|AA-0322 | 01-22-2015 |
|AA-0431 | 03-21-2014 |


Table parties:
|  id  |  docket  |  name  |
----------------------------
|   1  |  AA-0322 |  Bob   |
|   2  |  AA-0322 |  John  |


Table motions:
|  id  |  docket  |  motion |
-----------------------------
|  1   | AA-0322  |  Summons|
|  2   | AA-0322  |  Guilty |

我想计算派对和动作中具有相同文档的字段数,然后使用带有dt_file的table.cases创建一个表

示例:

| docket | party_count | motion_count| dt_file |
 -----------------------------------------------
  AA-0322|       2     |        2    | 02-22-2015|

我也想通过dt_file过滤,所以添加一个WHERE语句ex:

WHERE YEAR(dt_file) = '2015'

到目前为止,我已经提出了这个问题,但我没有成功地将table.cases与dt_file正确连接。

SELECT p.docket, p.party_count, m.motion_count
FROM
    (SELECT docket, COUNT(docket) AS party_count
     FROM parties
     GROUP BY docket) AS p
INNER JOIN
    (SELECT docket, COUNT(docket) AS motion_count
     FROM motions
     GROUP BY docket) AS m
ON p.docket = m.docket

3 个答案:

答案 0 :(得分:0)

您的查询似乎正确无误。您只需要将cases添加到from子句:

SELECT c.docket, p.party_count, m.motion_count, c.dt_file
FROM cases c JOIN
     (SELECT docket, COUNT(docket) AS party_count
      FROM parties
      GROUP BY docket
     ) p
     ON c.docket = p.docket INNER JOIN
     (SELECT docket, COUNT(docket) AS motion_count
      FROM motions
      GROUP BY docket
     ) m
     ON c.docket = m.docket;

如果你想要所有的游戏,即使那些没有动作或聚会的游戏,请使用LEFT JOIN

答案 1 :(得分:0)

这是另一个例子。

Select
    p.docket,
    COUNT(p.docket) As party_count,
    COUNT(m.docket) As motion_count,
    p.dt_file
From
    cases As c
        Inner Join  parties As p
            On  c.docket = p.docket
        Inner Join  motions As m
            On  c.docket = m.docket
Group By
    p.docket,
    p.dt_file

答案 2 :(得分:0)

试试这个:

func loadChildren(success: (Bool) -> ()) {
 // do stuff
}