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
SELECT *
FROM
( SELECT *
FROM table1
WHERE keyword LIKE '%s' OR id LIKE '%s' ---notice the quotes
UNION ALL SELECT .......
) AS tmp
ORDER BY keyword DESC
In such case I'd suggest you to normalize the database and put all the keywords in the same table. If you separate the keywords according to its type use a column type
to indicate it.
The following query will do what you are requiring.
SELECT *
FROM ((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')) AS bigtable
ORDER BY `id`;