简体   繁体   中英

Particular MySql Query

Having the following tables

Post(*id, name, description, cat, publish_date)
Category(*id, name)

It is possible in ONE query to get (max) the first N element of each different category?

Assuming that N=3, i'd need the following result:

Result set:

["1", "Name1","Descr","cat1"]
["2", "Name1","Descr","cat1"]
["3", "Name1","Descr","cat1"]
["10","Name1","Descr","cat2"]
["20","Name1","Descr","cat2"]
["22","Name1","Descr","cat2"]
["25","Name1","Descr","cat3"]
["30","Name1","Descr","cat3"]
["19","Name1","Descr","cat3"]

And so on.

I need this, to get the first N article of EACH category, with one query (so without ask for a specific category but for all category in table)

It is possible? If yes what's the right query?

You can use UNION to join multiple queries into one. This assumes that you know what type you are selecting for each set.

SELECT * FROM 
(
  SELECT * FROM T1 WHERE type='Type1' ORDER BY id DESC LIMIT 3
) DUMMY1

UNION ALL

SELECT * FROM 
(
  SELECT * FROM T1 WHERE type='Type2' ORDER BY id DESC LIMIT 3
) DUMMY2

UNION ALL

SELECT * FROM 
(
  SELECT * FROM T1 WHERE type='Type3' ORDER BY id DESC LIMIT 3
) DUMMY3

The DUMMY table aliases are needed to allow ordering within each subquery .

This query will do what you need. If any category has less than 3 post it will still work.

SELECT P.id,P.name,P.description,C.name 
FROM Post P
LEFT JOIN Category C
ON P.type = C.id
WHERE FIND_IN_SET(P.id,
    (
        SELECT GROUP_CONCAT(ids) FROM
            (SELECT SUBSTRING_INDEX(GROUP_CONCAT(id),',',3) as ids
                FROM Post 
                GROUP BY type
            ) AS foo
        GROUP BY ''
    )
)

Here is a working SQL Fiddle

UPDATE

In response to your comment and updated question:

SELECT P.id,P.name,P.description,P.publish_date,C.name 
FROM Post P
LEFT JOIN Category C
ON P.type = C.id
WHERE FIND_IN_SET(P.id,
    (
        SELECT GROUP_CONCAT(ids) FROM
            (SELECT SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY publish_date DESC),',',3) as ids
                FROM Post
                GROUP BY type      
            ) AS foo
        GROUP BY ''
    )
)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM