Biribu
Biribu

Reputation: 3823

Add a join in a UNION query MYSQL

I have this query with union all in mysql:

SELECT id_Event, pushToken, '' as phone, name, surname1 ai, surname2, NIF, year, city, status FROM signedup WHERE status = 0
UNION ALL
SELECT id_Event,'' as pushToken,  phone, name, surname1 ai, surname2, NIF, year, city, status FROM signedupLocal WHERE status = 0
ORDER BY ai ASC

Now, I created a new table (tableX) with some fields I want to add to each row. This new table has these fields:

id, id_Event, NIF, as1,as2,as3,as4

I want that each row in the first query get 4 new fiels (as1,as2,as3,as4), each one in the correct row. id_Event and NIF must match.

I guess I should add a join in each query but I am not sure how it will work.

Upvotes: 0

Views: 54

Answers (1)

Aziz Shaikh
Aziz Shaikh

Reputation: 16524

You are right, JOIN will be used. Wrap the UNION result into a table alias and then join with TableX. Try this:

SELECT as1,as2,as3,as4,y.id_Event, pushToken, phone, name, ai, surname2, y.NIF, year, city, status
FROM tableX
JOIN (
   SELECT id_Event, pushToken, '' as phone, name, surname1 ai, surname2, NIF, year, city, status 
   FROM signedup WHERE status = 0
   UNION ALL
   SELECT id_Event,'' as pushToken,  phone, name, surname1 ai, surname2, NIF, year, city, status 
   FROM signedupLocal WHERE status = 0
) y
ON tableX.id_Event = y.id_Event AND tableX.NIF = y.NIF
ORDER BY ai ASC

Upvotes: 2

Related Questions