Skip to main content
February 26, 2012
Answered

How to display database results from multiple tables in descending order?

  • February 26, 2012
  • 1 reply
  • 1115 views

I have a keyword search on my site that allows visitors to search for specific things. My msysql db has 15 tables and for the search feature I use a UNION ALL to join them all so visitor can search all the tables simultaneously. The problem is all the results are in ascending order. How do I get the results in descending order.

SELECT * 

FROM table1 

WHERE keyword LIKE %s OR id  LIKE %s 

UNION ALL

SELECT * 

FROM table2 

WHERE keyword LIKE %s OR id  LIKE %s 

UNION ALL

SELECT * 

FROM table3  

WHERE keyword LIKE %s OR id  LIKE %s

ps

I've tried this and it dosn't work:

SELECT * FROM table1 WHERE keyword LIKE %s OR id LIKE %s ORDER BY id DESC

and I know it's not conventional to use SELECT* with so many tables, but trust me I have my reasons. What i'm not trying to do is wrap all the UNION's inside an outer SELECT

This topic has been closed for replies.
Correct answer bregent

it's written exactly like this for all 15 tables

SELECT * 

FROM table1 

WHERE keyword LIKE %s OR id  LIKE %

Order By id DESC

UNION ALL

SELECT * 

FROM table2

WHERE keyword LIKE %s OR id  LIKE %

Order By id DESC


Once again,  the order by clause can only appear at then end of the last select statement in a UNION query. You have it on all of the select statements.

1 reply

Participating Frequently
February 26, 2012

>What i'm not trying to do is wrap all the UNION's inside an outer SELECT

Why not? That's really your only option, other than creating a view or sproc.

February 26, 2012

I didn't want to do that because I'm confused on how to do that. Would that involve rearranging all my sql statments. Are you sure that is my absolute last option, theres nothing like:

SELECT * 

FROM table1 

WHERE keyword LIKE %s OR tb_desc id  LIKE %s 

"that didn't work either by the way"

Participating Frequently
February 26, 2012

Sorry, maybe I misunderstood your original question. If you are just trying to order result set of a UNION operation, put the order by clause at the end of the last select statement.

>SELECT * 

>FROM table1 

> WHERE keyword LIKE %s OR tb_desc id  LIKE %s 

I have no idea what you are asking here. What is tb_desc?