문제

I have a query that follows this format:

(SELECT t.column1, t.column2
FROM table t 
WHERE t.status = 1 
LIMIT 10)
UNION
(SELECT t.column1, t.column2 
FROM table t
WHERE t.status = 2 
LIMIT 10)

The end result is that I need to have 20 rows. If the first SELECT statement can only find 9 rows with t.status = 1, then I would like the second SELECT statement to use LIMIT 11 instead of LIMIT 10

I am using PHP to write and run the query, but I am looking for something that will execute within MySQL so I can run it all as one query.

Any ideas would be greatly appreciated.

도움이 되었습니까?

해결책

Add one more limit 'outside' with the total count and use the same for the limit of the 2-nd query.

(
SELECT t.column1, t.column2
FROM table t 
WHERE t.status = 1 
LIMIT 10 # 1/2 of total rows
)
UNION
(
SELECT t.column1, t.column2 
FROM table t
WHERE t.status = 2 
LIMIT 20 # total rows
)
LIMIT 20 # total rows
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top