Question

I have little problem with my MySql query: I have two tables:

Table timeline

id | date      |  text
1    2013-10-13   Hello

Table reps

id | date      | text
1   2013-10-12   Its me again
1   2013-10-11   What?
1   2013-10-10   Lorem ipsum

What i am doing is UNION ALL timeline and reps.First row should always be the row from timeline(it's always one row) and then all rows from reps table but in DESC order.

My query is the following one(which work ok except from order by)

select id,date,text from timeline UNION ALL select * from reps order by date desc

Think something like a comment (sits on top) with replies on the comment in desc order,newest first.

Thank you in advance.

Was it helpful?

Solution

Put the UNION in a subquery:

SELECT id, date, text
FROM (SELECT id, date, text, 1 AS priority
      FROM timeline
      UNION ALL
      SELECT *, 2 AS priority
      FROM reps) u
ORDER BY priority, date DESC

OTHER TIPS

your query is right , you just close second query by () like that: and it will order just the second query . without () it will order the two queries.

   select id,date,text from timeline 
    UNION all
  (select * from reps order by date desc)

Make a Unix_timestamp from the date value and order by its value.

 SELECT -1 as 'id' , 99999999999999 as 'sortalias' , now() as 'datum||date'
 UNION
 ( SELECT
      id
      ,unix_timestamp(datum) as 'sortalias'
      ,datum as 'datum||date'
      FROM kunde
 )
 order by sortalias desc
select id,date,text from (
    select id,1 poid,date,text
    from timeline
    union all
    select id,2 poid,date,text
    from reps
) t
order by t.id asc,t.poid asc,t.date desc
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top