简体   繁体   中英

LIMIT on a condition in MySql

I am trying to get info from a table in this form :

table_1

jobid(PK) projectid desc
1            1      whatever
2            1         .
3            1         .
4            2         .
5            2         .
.            .         .
.            .         .

What I am trying to get is a query which will give me only 5 rows per projectid. ( a LIMIT on the WHERE statement but not on the whole SELECT)

If I use LIMIT, I get a total of 5 results.

What you can do is build the SQL in a dynamic form using the following query:

SELECT GROUP_CONCAT( 
  DISTINCT CONCAT(
    '(select jobid, projectid, desc from jobs where projectid=',
    projectid,
    ' order by jobid limit 5)') 
  SEPARATOR ' union ') AS q 
FROM table_1;

Save the result into a variable, and then execute the saved SQL.

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