我无法进行查询以获得某些交叉值。我对mysql的了解不太适合制作这类东西。
我有两个表,signedup和signedupLocal。两个字段相同:name,surname1,surname2,NIF,year,city,status和dateSigned。
我希望在surname1和surname2(A到Z)排序的状态为0时,将两个表中的所有值组合在一起。另外,我想要一个名为“app”的新字段,根据数据来自哪个表,它会显示是或否。如果是signedpupLocal,则是其他没有。
之后,当dateSigned(旧的第一个)命令状态为1时,我想做同样的事情。
到目前为止,我还没有尝试过测试一个完整的查询,因为我只有一部分问题。
我已尝试过类似的内容:
SELECT signedupLocal.name,
signedupLocal.surname1,
signedupLocal.surname2,
signedupLocal.NIF,
signedupLocal.year,
signedupLocal.city,
signedup.name,
signedup.surname1,
signedup.surname2,
signedup.NIF,
signedup.year,
signedup.city
FROM signedup, signedupLocal
WHERE signedup.id_Event = 78
AND signedupLocal.id_Event = 78
AND signedupLocal.status = 0
AND signedup.status = 0
但它失败了。
答案 0 :(得分:2)
SELECT name, surname1, surname2, NIF, year, city, status, 'no' as app,
case when status = 1 then datesigned else '2099-12-31' end as datesigned_sort,
case when status = 0 then surname1 else '' end as surname1_sort,
case when status = 0 then surname2 else '' end as surname2_sort
FROM signedup
WHERE id_Event = 78 AND status in(0,1)
UNION ALL
SELECT name, surname1, surname2, NIF, year, city, status, 'yes' as app,
case when status = 1 then datesigned else '2099-12-31' end as datesigned_sort,
case when status = 0 then surname1 else '' end as surname1_sort,
case when status = 0 then surname2 else '' end as surname2_sort
FROM signedupLocal
WHERE id_Event = 78 AND status in(0,1)
ORDER BY 7 asc, 9 desc, 10 asc, 11 asc
请注意,使用UNION
时,您需要使用列号,而不是ORDER BY
中的列名。我使用UNION ALL
因为它比UNION
更有效,因为后者删除重复项 - 这会导致数据库引擎的工作。所以如果你知道没有,你可以避免这种情况。
对于排序,我使用常量来表示不应按排序列对记录进行排序的情况。
答案 1 :(得分:1)
使用UNION
个2个查询来连接结果。
SELECT * FROM (
SELECT *, "signedup" AS tablename FROM signedup WHERE …
UNION
SELECT *, "signedupLocal" AS tablename FROM signedupLocal WHERE …
) U
ORDER BY U.dateSigned DESC