Please I have the following tables
Field
+----+--------+----------+---------------------+
| id | name | Type | date |
+----+--------+----------+---------------------+
| 1 | price | int | 2009-09-02 00:07:07 |
| 2 | width | float | 2009-09-02 00:07:08 |
| 3 | height| float | 2009-09-02 00:07:30 |
+----+--------+--------------------------------+
Post
+----+--------+---------------------------------+
| id |title | Body |
+----+--------+---------------------------------+
| 1 | test | Bla bla bla |
| 2 | Hello | Bla bla bla |
| 3 | Its me | Bla bla bla |
+----+--------+---------------------------------+
Post_Annex
+----+--------+----------+---------------------+
| id | IdPost | IdField | Value |
+----+--------+----------+---------------------+
| 1 | 1 | 1 | 50 |
| 2 | 1 | 2 | 21 |
| 3 | 1 | 3 | 3 |
| 4 | 2 | 1 | 10 |
| 5 | 2 | 2 | 2 |
| 6 | 2 | 3 | 150 |
| 7 | 3 | 1 | 1 |
| 8 | 3 | 2 | 25 |
| 9 | 3 | 3 | 15 |
+----+--------+--------------------------------+
And I desire to select data from the Post and Post_Annex tables, group them by the Id of the Post table and order them by the price (this mean by IdField of the Post_Annex table when its equal to 1). So this is my query :
SELECT p.title
FROM Post p
LEFT JOIN Post_Annex pa
ON p.id = pa.IdPost
GROUP BY p.id
ORDER BY case when pa.IdField = 1 then 0 else 1, pa.Value DESC
This gave me the result in this order : its Me | Hello | test
This is fine. But even if I try the order by the width (IdField = 2) or height (IdField = 3) it gave me the same result.
Please masters any Idea to help me resolving this ? Thanks in advance.
I would just modify the join clause, to specify which field you want to sort:
and then you don’t have to group by p.id.
Your query doesn’t always work because you are grouping by
p.idbut you are selecting (and ordering by) other nonaggregated columns, and the values of those columns can be undetemined.