简体   繁体   中英

Mysql result order by sum()

I have to tables:( id , name ) and another table ( id , id_name , money ).

In the second table I have something like that:

1, 1, 200
2, 1, 400
3, 2, 400

In the first table :

1,alex
2,jason

After I execute the query I want to receive this result :

alex,600

jason,400

This is my query:

SELECT tabel1.nume ,SUM(tabel2.money) FROM tabel2 JOIN tabel2 
    ON tabel1.id = tabel2.id_name
WHERE tabel1.id = tabel2.id_name ORDER BY SUM(money)

I receive just the first row from the second table.

WHere I do the mistake ??

You need to use GROUP BY

SELECT tabel1.name ,SUM(tabel2.money) 
 FROM tabel2 JOIN tabel2 ON tabel1.id = tabel2.id_name
 WHERE tabel1.id = tabel2.id_name 
GROUP BY tabel1.name
ORDER BY SUM(money)

If you use aggregate functions without GROUP BY , MySQL will group everything into single row.

You need to use group by when you use aggregate functions, using aggregate functions without grouping them will result in a single row by assuming the whole table as one group,according to your desired result set you also need DESC after ORDER BY clause

SELECT tabel1.id,
tabel1.nume ,
SUM(tabel2.money) `sum_money`
FROM tabel2 
JOIN tabel2 ON tabel1.id = tabel2.id_name 
GROUP BY tabel1.id
ORDER BY sum_money DESC
SELECT 
tabel1.nume,
SUM(tabel2.money) 
FROM tabel2 
JOIN tabel2 ON tabel1.id = tabel2.id_name
GROUP BY tabel1.nume
ORDER BY SUM(money)

You don't need to use where cluase here, you are doing this already on JOIN

You need to have a Group By in there

SELECT tabel1.id, tabel1.nume, SUM(tabel2.money) `sum_money`
FROM tabel2 JOIN tabel2 ON tabel1.id = tabel2.id_name
WHERE tabel1.id = tabel2.id_name 
GROUP BY tabel1.id
ORDER BY sum_money

First of all, look at your first line of the query:

  SELECT tabel1.nume ,SUM(tabel2.money) FROM tabel2 JOIN tabel2 

Unless you don't have column titled 'nume' in your first table, this tabel1.nume seems to be a typo, hence creating troubles. Besides, you are selecting from tabel2, joining with tabel2. This is wrong, you need to join with tabel1 instead of tabel2.

Secondly, consider your third line in the query:

  WHERE tabel1.id = tabel2.id_name

You don't actually need to put a WHERE clause here, since you are performing a join between tabel1 and tabel2 and so, you're using this line:

  ON tabel1.id = tabel2.id_name

Which actually substitutes the WHERE clause.

Thirdly, you need to use a GROUP BY clause in accordance with your tabel1.id. If you use GROUP BY , you no longer need to use ORDER BY .

To sum up, now your corrected query should look like this:

  SELECT tabel1.name ,SUM(tabel2.money) FROM tabel2 JOIN tabel1 
  ON tabel2.id_name = tabel1.id
  GROUP BY tabel1.id 

Hope this answered your question.

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