简体   繁体   English

在UNION查询MYSQL中添加联接

[英]Add a join in a UNION query MYSQL

I have this query with union all in mysql: 我在mysql中使用union all查询:

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. 现在,我创建了一个新表(tableX),其中包含我想要添加到每一行的一些字段。 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. 我希望第一个查询中的每一行得到4个新的fiels(as1,as2,as3,as4),每个都在正确的行中。 id_Event and NIF must match. id_Event和NIF必须匹配。

I guess I should add a join in each query but I am not sure how it will work. 我想我应该在每个查询中添加一个连接,但我不确定它是如何工作的。

You are right, JOIN will be used. 你是对的,将使用JOIN。 Wrap the UNION result into a table alias and then join with TableX. 将UNION结果包装到表别名中,然后与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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM