查询有关MySQL中的四个表

时间:2019-02-16 02:27:12

标签: mysql sql database

你好,我在数据库的4个表之间生成查询时遇到问题,首先我先解释一下表的结构以及它们之间的关系:

品牌

+--------------+
| id |  name   |
|--------------|
| 1  |  toyota |
| 2  |  suzuki |
| 3  |  mazda  |
+--------------+

汽车

+------------------------------------+
| id  | brand_id    | model          |
--------------------------------------
| 1   | 1           | XXXXX          |
| 2   | 2           | YYYYY          |
| 3   | 1           | ZZZZZ          |
+------------------------------------+

出租

+------------------------------------------------+
| id | car_id | date_init  | date_end   | amount |
--------------------------------------------------
| 1  | 1      | 2019-01-05 | 2019-01-12 |3000    |
| 2  | 2      | 2019-01-22 | 2019-01-30 |1800    |
| 3  | 3      | 2019-02-14 | 2019-01-26 |2500    |
+------------------------------------------------+

维护

+------------------------------------+
| id  | rental_id   | amount         |
--------------------------------------
| 1   | 3           | 600            |
| 2   | 3           | 320            |
| 3   | 2           | 180            |
+------------------------------------+

这些表基本上是在确定的时间内记录车辆的租金,该租金时间有明确的金额。细节在于,由于这个原因,您可以在租车期间对汽车进行任何或许多维护,因为我有维护表。我需要从查询中得到的是多少钱,以及包括维修金额在内的汽车模型产生的费用,我应该得到类似的东西:

+-----------------+
| brand   | total |
|-----------------|
| toyota  | 4000  |
| suzuki  | 3800  |
| mazda   | 2700  |
+-----------------+

我设法仅根据租金来获取金额,但是我不知道如何将维护表的金额关联起来,这就是我的查询内容:

select b.name as brand, sum(r.amount) as Total, m.mnt
from rental r
left join (
  select rental_id, sum(amount) as mnt
  from maintenance 
  group by m.rental_id
) as m on r.id = m.rental_id
inner join car c
on r.car_id = c.id
inner join brand b
on c.brand_id = b.id
group by b.name, m.mnt

考虑到我刚刚发布的查询,这就是答案:

+-------------------------+
| brand   | total |  mnt  |
|--------------------------
| toyota  | 3000  | NULL  |
| toyota  | 2500  | 920   |
| suzuki  | 1800  | 180   |
+-------------------------+

注意::将租金和维修费的金额划分到不同的列中,以便更好地理解该问题,最后,我需要在单个列中将这两个总数加起来。

1 个答案:

答案 0 :(得分:1)

您需要对每个表的总和使用子查询。然后,您可以加入他们,将rentalmnt组合在一起,然后按品牌对其求和。

SELECT b.name, SUM(r.rental + IFNULL(m.mnt, 0)) AS total
FROM brand AS b
JOIN car AS c on b.id = c.brand_id
JOIN (
  SELECT car_id, SUM(amount) AS rental
  FROM rental
  GROUP BY car_id) AS r ON r.car_id = c.id
LEFT JOIN (
  SELECT r.car_id, SUM(m.amount) AS mnt
  FROM rental AS r
  JOIN maintenance AS m ON m.rental_id = r.id
  GROUP BY rental_id) AS m ON m.car_id = r.car_id
GROUP BY b.id

DEMO

| name   | total |
| ------ | ----- |
| toyota | 6420  |
| suzuki | 1980  |