gpt4 book ai didi

mysql - 计算 2 个表的相等字段,并与第 3 个表进行内部连接

转载 作者:行者123 更新时间:2023-11-30 22:23:42 26 4
gpt4 key购买 nike

我有3张 table

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 |

我想计算具有相同摘要的政党和动议中的字段数,然后用 table.cases 和 dt_file 制作一个表格

例子:

| 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

最佳答案

您的查询似乎是正确的。您只需要将 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

关于mysql - 计算 2 个表的相等字段,并与第 3 个表进行内部连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35953561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com