Im having trouble in MySQL query Order By.
First I have a table(tbl_records) that contains 10000+ records. This table has a primary key called rec_id and a foreign key rec_f_id .
rec_f_id has only two kinds of value (555, 666).
Now my problem is how can I gather the records on the table that orders in alternate value of rec_f_id .
Eg
Below is a dummy tbl records
| rec_id | rec_f_id |
|2 |666 |
|3 |555 |
|7 |555 |
|8 |666 |
|9 |555 |
|12 |666 |
|25 |555 |
|31 |555 |
|84 |666 |
|89 |555 |
|91 |555 |
|92 |666 |
|113 |666 |
|118 |666 |
|125 |555 |
|132 |555 |
|170 |555 |
|184 |666 |
SELECT * FROM tbl_records ORDER BY FIELD(rec_f_id, 555, 666) LIMIT 100;
The above query only returns record with rec_f_id = 555. What I want to have is
| rec_id | rec_f_id |
|31 |555 |
|12 |666 |
|3 |555 |
|8 |666 |
|25 |555 |
|2 |666 |
|7 |555 |
|84 |666 |
|9 |555 |
...
Thanks!
try:
SELECT * FROM tbl_records
WHERE rec_f_id in (555,666)
ORDER BY rec_id, rec_f_id,
LIMIT 100;
Here's one option using user-defined variables
. Basically it creates a Row Number
per Group, and then orders by it along with the rec_f_id
field:
SELECT rec_id, rec_f_id
FROM (
SELECT rec_id, rec_f_id,
@rn:=IF(@prev=rec_f_id,@rn+1,1) rn,
@prev:=rec_f_id
FROM tbl_records
JOIN (SELECT @rn:=0, @prev:=0) t
ORDER BY rec_f_id
) t
ORDER BY rn, rec_f_id
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.