Domanda

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.

È stato utile?

Soluzione

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top