创建视图并从多个表中添加列值。那可能吗?
Users:
ID | FIRST NAME | LASTNAME |
1 | Mark | Lupez |
2 | James | Yap |
table1:
USER_ID | SCORE | GOAL |
1 | 7 | 9 |
2 | 4 | 6 |
table2:
USER_ID | SCORE | GOAL |
1 | 4 | 9 |
2 | 7 | 3 |
table3:
USER_ID | SCORE | GOAL |
1 | 2 | 3 |
2 | 3 | 2 |
我想添加
table1.score,table2.score,table3.score
其中
table1.user_id,table2.user_id,table3.user_id
等于Users表的ID列。
所以视图表创建的查询结果如下所示......
LASTNAME | FIRST NAME | SCORE | GOAL |
Lupez | Mark | 13 | 21 |
Yap | James | 14 | 11 |
我是mysql的新手,所以我对mysql语法的了解绝对是基本的。从多个表中添加对我来说是一个非常大的问题......
答案 0 :(得分:1)
我从您的示例数据中进行一些查询尝试此查询
(我不知道你为什么要分成3张桌子,我认为这不是一个好的设计)
SELECT u.ID
,u.LastName
,u.FirstName
,result.SCORE
,result.GOAL
FROM Users u
LEFT JOIN (
SELECT q.USER_ID ,SUM(q.SCORE) AS 'score' , SUM(q.GOAL) AS 'goal'
FROM (
SELECT t1.USER_ID,t1.SCORE,t1.GOAL
FROM table1 t1
UNION
SELECT t2.USER_ID ,t2.SCORE,t2.GOAL
FROM table2 t2
UNION
SELECT t3.USER_ID,t3.SCORE,t3.GOAL
FROM table3 t3
) q
GROUP BY q.USER_ID
) result
ON result.USER_ID = u.ID