Display 5 latest postgresql results

Asked

Viewed 413 times

0

I need to display the last 5 results of a query, but I do this query twice because I need to change the Where clause, to return the values I need.

I thought of something like:

SELECT id, project_id, name, subject FROM "issues" where project_id = 94 

UNION ALL 
    SELECT id, project_id, name, subject FROM "issues" where project_id = 95 

limit 5

But it didn’t work... Is there any way to make a query only and change its clause to display all the records I need ?

  • you couldn’t do so: SELECT id, project_id, name, subject from "issues" where project_id = 94 and project_id = 95 order by id desc limit 5 ???

2 answers

1


To solve your problem you can use the clause IN. It allows you to be informed a set of values for a test. In this case, your query would be:

SELECT id, project_id, name, subject FROM "issues" where project_id IN (94, 95) limit 5

The IN test if the value of the project_id is among any of the reported values (94 or 95) and if it is listed in the results.

  • Perfect @Giuliana, we thought together, was doing a test now before seeing the answers here from the site and saw that we reached the same conclusion, thank you !!

0

You can create a command SQL that meets your need:

SELECT id, project_id, name, subject from "issues" where project_id = 94 and project_id = 95 order by id desc limit 5

Where where project_id = 94 and project_id = 95 already checks the two conditions. Order by id desc take the latest information first. Limit 5 Take your last five on the case.

  • I’ve tried this before, but it didn’t work, because there’s no record of ID 94 and ID 95 at the same time, soon will return no record.

  • Ah good, it is that as this was not in the scope of the question I ended up not considering it

  • Anyway this is not possible :S, there is no way a record has two ID different, the ID is unique

Browser other questions tagged

You are not signed in. Login or sign up in order to post.