Jump to content

MySQL LIMIT per value help


MDanz

Recommended Posts

With the below query I'd get the results one and three. How do I get the results for `sid`; 15 and 17? I can't use a WHERE because I won't know the `sid`.

 

A better way of explaining is, how do I LIMIT per `sid` without grouping?

 

mysql_query("SELECT *
             FROM   `mytable`
             GROUP  BY `sid`
             ORDER  BY `sid` ASC
             LIMIT  0, 2");

+----+-----------+----------+
| id |       sid |      num |
+----+-----------+----------+
|  1 |        15 |      one |   
|  2 |        15 |      two |   
|  3 |        17 |    three |   
|  4 |        17 |     four |  
|  5 |        18 |     five |   
|  6 |        18 |      six | 

Link to comment
Share on other sites

this is what i want

 

+----+-----------+----------+
| id |       sid |      num |
+----+-----------+----------+
|  1 |        15 |      one |   
|  2 |        15 |      two |   
|  3 |        17 |    three |   
|  4 |        17 |     four |  

 

this is what i am getting

 

+----+-----------+----------+
| id |       sid |      num |
+----+-----------+----------+
|  1 |        15 |      one |   
|  3 |        17 |    three |   

 

basically i want to LIMIT per `sid`.  so LIMIT 2 will be two different `sid` not two rows.

Link to comment
Share on other sites

GROUP_CONCAT turns a field into a delimited list of items.

 

Combine that with SUBSTR and other string manipulation functions and you can:

1)  use group_concat to make your third column a comma-delimited list of all the num fields.

2)  use strpos (or equivalent) to find the location of the second comma

3)  Use substr to limit your delimited list to the characters up to the second comma (effectively, the first two elements)

 

-Dan

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.