简体   繁体   中英

order by sum of column in other table with where clause

I am using codeigniter and I want to list campaigns order_by how many donations each has received. So we are dealing with two tables, "campaigns" and "donations".

I used this

$this->db->select('campaigns.id as id, campaigns.userId as userId, name, amount');
$this->db->join('donations','donations.campaignId = campaigns.id', 'left');
$this->db->order_by("SUM(amount)", "DESC");

I want it to get all campaigns whether they have any donations or not and order by sum of the donations they have received. This query is getting just one campaign. Ideas?

You need a group by campaigns.id and to change the select to have sum(amount) as amount .

This is a SQL problem. I'm not intimately familiar with code-igniter so I won't attempt to write the code.

i think you are trying to get sum of donations in donation table with each campaigns.If i am right the the query should like below.

SELECT campaigns.*, sum(donation.donation) as donation_received FROM `donation`,`campaigns` WHERE campaigns.id=donation.cam_id group by donation.cam_id order by sum(donation.donation) desc

if it works for you i can write it in codeignter for you.please let me know the status.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM