Skip to content
Advertisement

Combine two queries from different tables and sort by a common column?

I have this two queries

SELECT  consejos.consejo as value,
                            consejos.id,
                            consejos.texto,
                            consejos.votos               
                    FROM consejos
                    ORDER BY fecha DESC

And

SELECT  preguntas.pregunta as value,
                            preguntas.id,
                            preguntas.texto,
                            preguntas.votos               
                    FROM preguntas
                    ORDER BY fecha DESC

Is there any simple way to get both results in the same query and sort by fecha column? and would it be possible to add a field to determinate which table is a row from?

Advertisement

Answer

you can use union:

SELECT value, id, texto, votos, source_table from (
  SELECT  consejos.consejo as value,
                              consejos.id,
                              consejos.texto,
                              consejos.votos,
                              'consejos' as source_table,
                              fecha               
                      FROM consejos
UNION
  SELECT  preguntas.pregunta as value,
                              preguntas.id,
                              preguntas.texto,
                              preguntas.votos,
                              'preguntas' as source_table,
                              fecha                              
                      FROM preguntas
) as A ORDER BY fecha DESC

EDIT: for your additional request, to add a column indicating from which table it came- you can just add to the columns list in the select 'consejos' as source_table to the first, and 'preguntas' as source_table to the second

Second EDIT (for strawberry, is this a test or something? did I pass :)?) add fecha to the inner queries, but not to the wrapping one if you dont want it there

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement