select * from ( select * from y where x="t") where z rlike "(.*)query1"
union
select * from ( select * from y where x="t") where z rlike "(.*)query2"
As you can see above, parenthesis contain the same query which typically
returns multi-row results. Is there any way to optimize it by only querying once for the select statement inside the parenthesis and using the result over and over again?
PS: I want to get the results in an ordered manner, so the results of the first unioned query must stay at top.
Three things here:
UNIONif you can useUNION ALL. Plainunions involve removal of duplicates and thus take more time.OR.select * from (select * ...is redundancy and can be avoided.Which gives:
As said in a comment by melpomene (thanks!) you can even factor at the regex level:
WHERE z RLIKE '(.*)query1|(.*)query2'If there are duplicates in
yand you don’t want them, sinceUNIONdiscarded them, you can introduceDISTINCTbut avoid if it is not necessary.If you want an order, never rely on the DBMS. Use
ORDER BY: