Make selection from the results obtained from the same

1

Good afternoon,

I have the following table ..

*eventos*
----------------------------------------
| id_evento | id_projeto | nome_evento |
----------------------------------------

I need to do a procedure as follows:

"Select events where the project_id is 1 with a 2-record limit, but if the number of records is less than 2, select the last events logged to complete the total amount of 2 records. "

I need to select the records that have given id_projeto but if by chance there is no record (with this id) I need to select the last two of the events table, and if there is only 1 then I need to select only 1 record.

I hope I have been clear. Any questions I answer.

obs: I'm using the mysql database

    
asked by anonymous 23.10.2017 / 22:38

2 answers

3

Use ORDER BY FIELD next to LIMIT to do this:

SELECT * FROM eventos ORDER BY FIELD(id_projeto, 1) DESC, id_evento DESC LIMIT 2
    
23.10.2017 / 23:10
3

Considering the query by id_projeto = 1 can be done this way:

select 
id_evento,id_projeto,nome_evento, 1 as prioridade
from eventos where id_projeto =1

union

select 
id_evento,id_projeto,nome_evento, 2 as prioridade
from eventos where id_projeto !=1

order by prioridade, id_evento desc
limit 2;

I put it in SQLFiddle: link

    
23.10.2017 / 23:28