0

I have a query which is a UNION of two Queries:

SELECT first_name, last_name, email
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.promoter = true
AND o.ticket = 'HOTEL'

UNION ALL

SELECT first_name, last_name, email
FROM users u
WHERE u.id IN (
'232drt-erty3-dff3',
'sswer3-ddf33-675t',
'we2311-23xxw-11vb'
)

I would like to know if is it possibile to define the two queries as variables and call them Q1 and Q2 So that my query becomes something like

SELECT *
FROM (
Q1 UNION ALL Q2
)
Fabio Manniti
  • 151
  • 12
  • I'm not sure your mysql version, nor how you are using this query, but it sounds like you want a Common Table Expression (CTE) ~ https://stackoverflow.com/q/1382573/1462295 – BurnsBA Aug 18 '22 at 13:14
  • Stored procedure may receive these queries as text parameters and execute them in solid query using dynamic SQL (PREPARE statement). – Akina Aug 18 '22 at 13:22
  • Short answer no - is there a question behind the question? – P.Salmon Aug 18 '22 at 13:48
  • You can write queries in string variables, concatenate them or modify in any way and then execute as prepared statement. But why would you want to do that for something like above? Maybe there is a better solution for the real problem, like (as already mentioned) CTE. – Paul Spiegel Aug 18 '22 at 14:12
  • CTE is actually the best solution. Thank you – Fabio Manniti Aug 18 '22 at 14:57

0 Answers0