I want to select the last 3 news from each category, from two table
first table ' Categories ' & ' news '
categories table
ID_CAT | NAME | PRIORITE
News table
ID | ID_CAT | TITLE | THE_NEWS
I try to do limit in this SQL code, but it gives me just the last 3 news from all categories
SELECT C.PRIORITE, N.*
FROM categories C, news N
WHERE N.ID_CAT=C.ID_CAT
AND C.PRIORITE >1
ORDER BY N.ID DESC
LIMIT 3
I try to get all news that have PRIORITE > 1
( The priorite is the order of category ) So, I want to get 3 last news from each priorite.
Example :
Priorite 2 = get last 3 news
Priorite 3 = get last 3 news
... etc
I made some search on the internet, but nothing worked for me, is there any solution? Or do I need to create another function to get news from each category with ID sending in parameters of it?
You could get n no. of news for each category by using a correlated sub query
SELECT *
FROM news n
JOIN categories c ON c.id = n.category_id
WHERE c.priority > 1
AND (
SELECT COUNT(*)
FROM news
WHERE n.category_id = category_id
AND n.id <= id
) <= 3;
Or if you are using Mysql 8 then you could make use of window functions with common table expressions like
WITH cte AS(
SELECT *,
RANK() OVER (PARTITION BY category_id ORDER BY id DESC ) rnk
FROM news
ORDER BY id
)
SELECT *
FROM cte n
JOIN categories c ON c.id = n.category_id
WHERE c.priority > 1
AND rnk <= 3;
i suggest divide it 2 parts, instead of complex query,
in 1st part you can get categories
select * from Categories
then loop categories and in loop get their 3 news,
select * from news where cat_id = '' order by desc id limit 3
if you try both and check the execution time, you see loop take less time. because news are rapidly growing stuff. i know you think why i call query again and again but my teacher said prefer multiple queries instead of complex one
Try this query, it should work:
SELECT
C.PRIORITE, N.*
FROM
categories C
JOIN news N ON N.ID_CAT=C.ID_CAT
AND C.PRIORITE >1
GROUP BY
C.ID_CAT
HAVING
COUNT(*) <= 3
ORDER BY N.ID DESC
Lemme know if there's any problem with that.
Try this query. This query generate a row number for each record based on the PRIORITE. Then return row number equal or less than 3.
SELECT ID, PRIORITE, THE_NEWS
FROM
(
SELECT ID, PRIORITE, THE_NEWS ,
@rn := IF(@prior = PRIORITE, @rn + 1, 1) AS rn,
@prior := PRIORITE
FROM(
SELECT t.*,c.PRIORITE FROM news t
LEFT JOIN categories c ON t.ID_CAT=c.ID_CAT ) e
CROSS JOIN (select @rn:=0, @prior:=null) c
ORDER BY PRIORITE,ID desc
) as x
WHERE x.rn <= 3 ;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.