[英]Select SUM of columns in unrelated tables in one query
I have these tables which are not related at all:我有这些根本不相关的表:
Books Apps Cars
Id Views Id Views Id Views
------------ ------------ ------------
1 3 4 5 11 10
2 4 5 100 13 3
3 3 6 5 15 7
I want:
total_books total_apps total_cars
10 110 20
Instead of 3 separate queries for the sum of views, I would like to have 1 query where I will get the sum of views in each table我希望有 1 个查询,而不是 3 个单独的视图总和查询,我将在其中获取每个表中的视图总和
SELECT SUM(books.views), SUM(apps.views), SUM(cars.views) FROM books,apps,cars;
giving me NULL NULL NULL
You would still need multiple selects since the tables are not related.由于表不相关,您仍然需要多次选择。
Try this (credits to this answer ):试试这个(归功于这个答案):
SELECT * FROM (SELECT SUM(Views) as total_books from Books) as Books, (SELECT Sum(Views) as total_apps from Apps) as Apps, (SELECT Sum(Views) as total_cars from Cars) as Cars
There are probably better/more performant ways to accomplish this, but at least it is a start.可能有更好/更高效的方法来实现这一点,但至少这是一个开始。
If I run the same command you did, the results are multiplied by 9 instead (see it here ).如果我运行与您相同的命令,结果将乘以 9(参见此处)。
I just realized your results are coming back as null. So as pointed out by others, your table must be empty.我刚刚意识到您的结果返回为 null。正如其他人所指出的,您的桌子一定是空的。 In my examples, I created the Views field as
NOT NULL
so I would never run into what you did.在我的示例中,我将 Views 字段创建为
NOT NULL
,因此我永远不会遇到您所做的事情。
It would be useful to provide additional information about where you are running your queries.提供有关您在哪里运行查询的附加信息会很有用。 Could you be accidentally running the queries against a different version of the tables (maybe a different context window in your software)?
您是否会不小心针对不同版本的表运行查询(可能是您软件中的不同上下文 window)?
SELECT
(SELECT SUM(Views) from Books) as Books,
(SELECT Sum(Views) from Apps) as Apps,
(SELECT Sum(Views) from Cars) as Cars ;
(No need for 'derived' tables.) (不需要“派生”表。)
Some databases (other than MySQL) may need FROM DUAL
on the end.某些数据库(MySQL 除外)可能需要
FROM DUAL
最后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.