1

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.

4 Answers 4

7

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
5
  • you have to order by id first
    – Jonysuise
    Oct 13, 2013 at 21:05
  • @Jonysuise Huh? Why so? Oct 13, 2013 at 21:06
  • I don't see any mention of that in the question. He said timeline just has one row. I suspect his actual query has where id = ... in both subqueries, so he's not showing all IDs.
    – Barmar
    Oct 13, 2013 at 21:07
  • assuming the id of the reps table is the fk of the id of the timelines table... :(
    – Jonysuise
    Oct 13, 2013 at 21:08
  • Worked like charm! Thank to all the other too! Oct 13, 2013 at 21:10
1

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)
2
  • 2
    Not my downvote, but will UNION ALL guarantee that the result on the left hand side stays before all results on the right hand side? Oct 13, 2013 at 21:05
  • @JoachimIsaksson if you select it first then it comes first .
    – echo_Me
    Oct 13, 2013 at 21:07
0

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
-1
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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.