简体   繁体   中英

Can't figure out how to write this query

I have a couple hundred records in a table and I need to get the the last 50 of them, but I need 25 males and 25 females. There is a gender column. I just can't figure out how to make that query. Can I get some help?

If you need exactly 50, use a UNION which gets the last 25 of each. This assumes you have some auto-incrementing id column which is sorted in descending order to retrieve the newest 25 of each gender.

In order to use an ORDER BY and LIMIT for individual components of a UNION , MySQL expects those components to be enclosed in () .

(SELECT * FROM tbl WHERE gender='F' ORDER BY id DESC LIMIT 25)
UNION ALL
(SELECT * FROM tbl WHERE gender='M' ORDER BY id DESC LIMIT 25)

Note : By the way, I've used SELECT * here for brevity but you should never actually do that in a UNION query. Instead, explicitly list the columns you need, and make sure they're in the same order in both parts of the UNION .

Like:

(SELECT col1, col2, coln FROM tbl WHERE gender='F'....)
UNION ALL
(SELECT col1, col2, coln FROM tbl WHERE gender='M'....)
(SELECT * FROM table WHERE gender = 'M' ORDER BY id DESC LIMIT 25)
UNION
(SELECT * FROM table WHERE gender = 'F' ORDER BY id DESC LIMIT 25)

That would work I guess. For the order by ID part I assumed you have an autoincrement id column, making the last added records the ones with the highest ID.

I just thought of this quickly, no guarantees.

SELECT * FROM table WHERE gender = 'male' ORDER BY ID DESC LIMIT 25
UNION ALL
SELECT * FROM table WHERE gender = 'female' ORDER BY ID DESC LIMIT 25

Basically, it gets the last 25 men, and the last 25 women, and combines the results together.

there is no such concept of LAST unless you have another column which you can use to ORDER BY .

i suggest write 2 queries, on for males only, and another for females only.

then use an order by so there is a 'last' set.

then flip that (using DESC ) so they are FIRST instead.

then use LIMIT clause to select the number you want.

then finally, UNION them together.

Try using two queries, one to grab the 25 latest males and a second to grab the 25 latest females. Then just concatenate the results.

SELECT * FROM males LIMIT 25 ORDER BY DESC

SELECT * FROM females LIMIT 25 ORDER BY DESC

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