简体   繁体   English

从两个不同的表中减去列的值

[英]Subtracting values of columns from two different tables

I would like to take values from one table column and subtract those values from another column from another table. 我想从一个表列中获取值,并从另一个表中的另一列中减去这些值。

I was able to achieve this by joining those tables and then subtracting both columns from each other. 我能够通过连接这些表然后相互减去两列来实现这一点。

Data from first table: 第一张表中的数据:

SELECT max_participants FROM courses ORDER BY id;

Data from second table: 第二张表中的数据:

SELECT COUNT(id) FROM participations GROUP BY course_id ORDER BY course_id;

Here is some code: 这是一些代码:

SELECT max_participants - participations AS free_places FROM
(
SELECT max_participants, COUNT(participations.id) AS participations
FROM courses
INNER JOIN participations ON participations.course_id = courses.id
GROUP BY courses.max_participants, participations.course_id
ORDER BY participations.course_id
) AS course_places;

In general, it works, but I was wondering, if there is some way to make it simplier or maybe my approach isn't correct and this code will not work in some conditions? 一般来说,它有效,但我想知道,如果有一些方法可以使它更简单,或者我的方法可能不正确,这些代码在某些条件下不起作用? Maybe it needs to be optimized. 也许它需要优化。

I've read some information about not to rely on natural order of result set in databases and that information made my doubts to appear. 我已经阅读了一些关于不依赖数据库中结果集的自然顺序的信息,这些信息使我怀疑出现。

If you want the values per course , I would recommend: 如果你想要每门课程的价值,我会建议:

SELECT c.id, (c.max_participants - COUNT(p.id)) AS free_places
FROM courses c LEFT JOIN
     participations p
     ON p.course_id = c.id
GROUP BY c.id, c.max_participants
ORDER BY 1;

Note the LEFT JOIN to be sure all courses are included, even those with no participants. 请注意LEFT JOIN以确保包含所有课程,即使没有参与者也是如此。

The overall number is a little tricker. 整体数字有点小问题。 One method is to use the above as a subquery. 一种方法是使用上面的子查询。 Alternatively, you can pre-aggregate each table: 或者,您可以预先聚合每个表:

select c.max_participants - p.num_participants
from (select sum(max_participants) as max_participants from courses) c cross join 
     (select count(*) as num_participants from participants from participations) p;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM