[英]How to get data from two tables like one table all rows and with respect to first table primary key sum of row from other table
Table 1: 表格1:
Table 2: 表2:
Result table: 结果表:
I am in the need of efficient result as my original table one have 100 columns so I need to use aysteric (*). 我需要高效的结果,因为我的原始表有100列,因此我需要使用aysteric(*)。 I'm currently working in
mysql
. 我目前在
mysql
工作。
Use an aggregation query: 使用聚合查询:
SELECT
t1.id,
t1.Name,
t1.Email,
t1.Address,
t1.Designation
COALESECE(t2.expenses, 0) AS Expense
FROM Table1 t1
LEFT JOIN
(
SELECT user_id, SUM(Expense) AS expenses
FROM Table2
GROUP BY user_id
) t2
ON t1.id = t2.user_id;
We could also write the above without a subquery, using a direct join with aggregation. 我们也可以使用带有聚合的直接联接来编写上面没有子查询的代码。 But, with so many columns having appear in the
GROUP BY
clause, I prefer the version I gave. 但是,由于
GROUP BY
子句中出现了许多列,因此我更喜欢给出的版本。
You can directly join sum of expense table of each user by using below query. 您可以使用下面的查询直接加入每个用户的费用总和表。
SELECT userdata.*, (select sum(expense) from expense where expense.user_id=userdata.id) as expense FROM `userdata`
Or by using left join 或使用左联接
SELECT u.*, sum(e.expense) as expense FROM `userdata` u left join expense e on e.user_id=u.id group by u.id
Here is the full Example of above query (NOTE - PLEASE CHANGE COLUMN NAME ACCORDING TO YOUR TABLE STRUCTURE) . 这是上述查询的完整示例(根据您的表结构,请注意更改列名称) 。
User table 用户表
Expense Table 费用表
Then run the query 然后运行查询
SELECT userdata.*, (select sum(expense) from expense where expense.user_id=userdata.id) as expense FROM `userdata`
Response 响应
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.