多表查詢能統計排序,怎麼寫

來源:互聯網
上載者:User
會員表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;

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.