Home >Backend Development >PHP Tutorial >请教大家三表连接查询的sql怎么写

请教大家三表连接查询的sql怎么写

WBOY
WBOYOriginal
2016-06-06 20:39:311215browse

有如下三张表(第一行为字段名)

user用户表:

id name
1 aaa
2 bbb
3 ccc

chargeRecord充值记录表:

id userId money
1 1 10
2 1 2
3 2 4
4 2 6

record通话记录表:

id callId(主叫) beCallId(被叫) time(时长)
1 2 1 23
2 3 1 2
3 2 3 16

如何利用user表里面的id 和充值记录表的userId 以及record表的callId/beCallId做连接
查询 用户名,充值总金额,和通话总时长(主叫时长)
新手谢过大家了!!

回复内容:

有如下三张表(第一行为字段名)

user用户表:

id name
1 aaa
2 bbb
3 ccc

chargeRecord充值记录表:

id userId money
1 1 10
2 1 2
3 2 4
4 2 6

record通话记录表:

id callId(主叫) beCallId(被叫) time(时长)
1 2 1 23
2 3 1 2
3 2 3 16

如何利用user表里面的id 和充值记录表的userId 以及record表的callId/beCallId做连接
查询 用户名,充值总金额,和通话总时长(主叫时长)
新手谢过大家了!!

<code>SELECT user.id AS id, user.name AS name, charge.money AS money, record.time AS time
FROM user
LEFT JOIN (SELECT userId, SUM(money) AS money FROM chargerecord GROUP BY userId) AS charge ON user.id = charge.userId
LEFT JOIN (SELECT callId, SUM(time) AS time FROM record GROUP BY callId) AS record ON user.id = record.callId
ORDER BY user.id
</code>

请教大家三表连接查询的sql怎么写

怎么查 楼上已经给出了 我有一篇关于多表查询的文章 希望对楼主了解多表查询有帮助:SQL的几种连接:内连接、左联接、右连接、全连接、交叉连接

各位 如果不喜欢这个答案 给评论回复 我撤掉回复 求别踩

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn