Guns_Roses
Guns_Roses

Reputation: 165

sql query with UNION order by issue

i want to make an Order By query but i don't know why it's not working this is my query i dont know where to put order by , i tested with every single select , not working , tested to put it at the last query no changes , can you help me on that ? i want to have order by a.id

$data = null;
                         $sth = Model::connect()->prepare(" SELECT a.*, b.ciudad, d.catgoria, d.categorie, e.mark AS marka , c.fuel FROM table1 a, 
                             fuel c ,ciudad b,  table2 d  , coches e WHERE 
                             a.ciudad = b.id_vil AND a.mark = e.id AND a.fuel = c.id AND d.id = a.table3 AND a.status = 1  

                             UNION 
                              SELECT a.*, b.ciudad, d.catgoria, d.categorie, e.mark AS marka , c.fuel FROM table1 a, 
                             fuel c ,ciudad b,  table2 d  , liste_vehicules_marchandises e WHERE 
                             a.ciudad = b.id_vil AND a.mark = e.id AND a.fuel = c.id AND  d.id = a.table3 AND a.status = 1  
                             UNION 
                             SELECT a.*, b.ciudad, d.catgoria, d.categorie, e.mark AS marka , c.fuel FROM table1 a, 
                             fuel c ,ciudad b,  table2 d  ,  liste_vehicules_agricultures e WHERE 
                             a.ciudad = b.id_vil AND a.mark = e.id AND a.fuel = c.id AND d.id = a.table3 AND a.status = 1  
                             UNION 
                              SELECT a.*, b.ciudad, d.catgoria, d.categorie, e.mark AS marka , c.fuel FROM table1 a, 
                             fuel c ,ciudad b,  table2 d  , bc_vehicule e WHERE 
                             a.ciudad = b.id_vil AND a.mark = e.id AND a.fuel = c.id AND d.id = a.table3 AND a.status = 1  


                             ");
                                                                    $sth->execute();
                                                                    $data = $sth->fetchAll();
                       return $data;

Upvotes: 0

Views: 38

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270713

You would add:

order by id

as the last line in the query.

Also, I would recommend that you use UNION ALL instead of UNION, unless you specifically want to incur the overhead of removing duplicates.

Upvotes: 1

Related Questions