我在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
现在,我创建了一个新表(tableX),其中包含我想要添加到每一行的一些字段。这个新表包含以下字段:
id, id_Event, NIF, as1,as2,as3,as4
我希望第一个查询中的每一行获得4个新的fiels(as1,as2,as3,as4),每个都在正确的行中。 id_Event和NIF必须匹配。
我想我应该在每个查询中添加一个连接,但我不确定它是如何工作的。
答案 0 :(得分:2)
你是对的,将使用JOIN。将UNION结果包装到表别名中,然后与TableX连接。试试这个:
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