mysql - 如何从 MySQL 中没有任何关系的两个表中获取记录?

标签 mysql

我有两个表。

包含这些列的表 1 (abc)

 ____________________________
|__id__|__userid__|__points__|
|__1__ |_____2____|____30____|
|__2__ |_____2____|____50____|
|__3__ |_____3___ |____40____|

表 2(xyz)

 ________________________________
|__id__|__userid__|__usedpoints__|
|__1__ |_____2____|______10______|
|__2__ |_____3____|______20______|
|__3__ |_____2___ |______15______|

如何从这两个表中获取这样的记录?

 _________________________________________
|__userid__|__totalpoints__|__usedpoints__|
|____2____ |_______80______|______25______|
|____3____ |_______40______|______20______|

最佳答案

select u1.userid, sum(u1.points) as totalpoints, u2.usedpoints
from table1 u1
left join 
(
   select userid, sum(usedpoints) as usedpoints
   from table2
   group by userid
) u2 on u1.userid = u2.userid
group by u1.userid  

SQLFiddle demo

关于mysql - 如何从 MySQL 中没有任何关系的两个表中获取记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28083788/

相关文章:

ASP.net GridView 获取数据库值

java - 错误 1126 (HY000) : Can't open shared library 'lib_mysqludf_sys.dll' (errno: 126) The specified module could not be found. )

mysql - 批处理 : grep equivalent

php - 使用 PDO 从 MySQL 获取结果

MySQL 正则表达式运算符 "maybe is there"

php - 如何在mysql中编辑序列化内容

mysql - SQL Pro 将 DATETIME 转换为 DATE

当至少满足 x 列中的条件时,MYSQL 选择行?

php - MySQL查询获取最新结果加上记录数

php - 在 mysql 字段之间交换/交换值