使用左连接和内连接从三个表中获取数据

时间:2018-01-24 15:57:04

标签: mysql sql left-join inner-join

我有三张桌子。

managersTbl

ID   | NAME |
1    | Ana  |
2    | Elsa |
3    | Olaf |
4    | Belle|

gigsTbl

ID   | GIG       | EARNING | MANAGER | ARTIST |
1    | sing      | 500     | 2       | 1      |
2    | act       | 100     | 2       | 3      |
3    | modelling | 250     | 3       | 4      |
4    | dance     | 10      | 1       | 1      |

artistsTbl

ID   | NAME   |
1    | Haley  |
2    | Aw     |
3    | Fire   |
4    | Finn   |

我想要完成的是获得所有经理,并获得他们的演出总和。

SELECT  id, name
ifnull(b.earning, 0) AS earning
FROM doctorsTbl
LEFT JOIN(
    SELECT id, name
    SUM(earning) AS earning
    FROM gigsTbl
    GROUP BY manager_id
) b on (a.id = b.manager_id)

我已经通过上述查询获得了所有经理以及他们的演出收入总和。现在,我希望从他们的经理分组的gigsTbl中获取所有艺术家,而不是重复。

我尝试过像这样使用内连接

SELECT  id, name
ifnull(b.earning, 0) AS earning
FROM doctorsTbl
LEFT JOIN(
    SELECT id, name
    SUM(earning) AS earning
    FROM gigsTbl
    INNER JOIN artistsTbl d
    on b.artist = d.id
    GROUP BY manager_id
) b on (a.id = b.manager_id)

我想在不为艺术家创建新查询的情况下执行此操作,因为我希望能够使用艺术家标识搜索表格。

0 个答案:

没有答案