How to select 5 separate lines

How to select 5 lines, 1 for each site_id, this causes an error

SELECT DISTINCT site_id, * 
FROM deal 
WHERE site_id IN (2, 3, 4, 5, 6) 
ORDER BY id 
DESC LIMIT 5

You have an error in the SQL syntax; check the manual that matches your MySQL server version for the correct syntax to use next to * * FROM deal WHERE site_id IN (2, 3, 4, 5, 6) ORDER BY id DESC LIMIT 5 'on line 1 "

+3
source share
4 answers

Try using GROUP BY

SELECT * 
FROM deal 
WHERE site_id IN (2, 3, 4, 5, 6) 
GROUP BY site_id
ORDER BY id DESC
LIMIT 5;
+4
source

If your table allows you to duplicate site_ids, and you only need to show one on the site_id, then provided that the identifier is unique

SELECT * FROM deal
WHERE id in (
    SELECT max(id) maxid
    FROM deal
    WHERE site_id IN (2, 3, 4, 5, 6)
    GROUP by site_id
)
+1
source

() . ( .) . ( .)

SELECT * FROM deal
WHERE id in (
    SELECT max(id) maxid
    FROM deal
    WHERE site_id IN (2, 3, 4, 5, 6)
    GROUP_BY site_id
)

, .

     WHERE site_id IN (2, 3, 4, 5, 6)
+1
source

You cannot specify DISTINCT site_id, nor can you include * a wildcard. If you want to specify a separate site_id file, you need to remove the wildcard and specify the other fields that you want to use.

0
source

Source: https://habr.com/ru/post/1789145/


All Articles