Home >Backend Development >PHP Tutorial >多表查询能统计排序,怎么写

多表查询能统计排序,怎么写

WBOY
WBOYOriginal
2016-06-23 13:07:08918browse

会员表A  字段: userid,username
内容:
1 张三 
2 李四 


消费记录表B  字段: userid,username,money,type
内容:
1 张三  100 1
1 张三  100 1
2 李四  100 1
2 李四  100 2


要求:按type=1类型显示各个会员的总消费,并按消费金额排序

结果如:
张三  200元
李四  100元


回复讨论(解决方案)

select t.username,sum(t.money) as sum1 
from table t
where t.type=1
group by t.username
order by sum1 desc

select sum(b.money) from b left join a.userid=b.userid where b.type=1 order by sum(b.money) desc

select  username,sum(money) as total from 消费记录表B  where type=1 group by username order by total desc

$strsql="select * from B where type=1"; $result=mysql_db_query($mysql_database, $strsql, $conn); mysql_data_seek($result, 0); $re = array();while ($row=mysql_fetch_row($result)) { 	isset($row['userid']) && $re[$row['userid']] += $row['money'];	isset($row['userid']) || $re[$row['userid']] = $row['money'];} foreach($re as $key=>$value) {echo $value['username'].' '.$value['money'];}// 释放资源 mysql_free_result($result); // 关闭连接 mysql_close($conn); 


你的B表里边已经包含了A表的内容,有必要关联两个表吗

select username,sum(money) as total from 消费记录表B where type=1 group by userid order by total desc;

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