如果部分返回没有结果,则整个联合查询不返回任何结果

时间:2012-11-30 08:40:34

标签: sql ms-access ms-access-2007 criteria

我创建了以下的Union查询,大部分时间都可以正常运行:

SELECT [%$##@_Alias].[Contact ID], [%$##@_Alias].[Mailing Name]
FROM (SELECT [Referrals - Contacts Within Organisations].[Contact ID], [Referrals - Contacts Within Organisations].[Mailing Name],  [Referrals - Contacts Within Organisations].[Surname], [Referrals - Contacts Within Organisations].[First name]
FROM [Referrals - Contacts Within Organisations]
UNION SELECT "0" as [Contact ID], "View all contacts" as [Mailing Name], "0" as [Surname], "0" as [First name]
FROM [Referrals - Contacts Within Organisations])  AS [%$##@_Alias]
ORDER BY [%$##@_Alias].Surname, [%$##@_Alias].[First name];

这会在查询返回的顶部添加“查看所有联系人”的初始行。

但是,如果它的“实际”查询部分没有返回任何结果,则整个查询不返回任何结果,而我总是希望无论如何都显示初始行。

这是可能的,如果是的话,我做错了什么?感谢。

编辑:谢谢大家的帮助。最终的工作查询在下面供其他需要此类事情的人参考:

SELECT A.[Contact ID], A.[Mailing Name]
FROM (SELECT "0" as [Contact ID], "View all contacts" as [Mailing Name], "0" as [Surname], "0" as [First name]
FROM [Dummy] 
UNION
SELECT [Referrals - Contacts Within Organisations].[Contact ID], [Referrals - Contacts Within Organisations].[Mailing Name],  [Referrals - Contacts Within Organisations].[Surname], [Referrals - Contacts Within Organisations].[First name]
FROM [Referrals - Contacts Within Organisations]) AS A
ORDER BY A.Surname, A.[First name];

1 个答案:

答案 0 :(得分:1)

要在SQL中始终返回包含数据的行,即使您手动提供值,也需要从至少有一行的表中进行选择,我建议使用 tblDummy 一个随机信息领域。

e.g:

SELECT "Hello", "Goodbye"
FROM tblDummy

作为旁注,我也会尝试摆脱:

[%$##@_Alias]

这可以通过添加:

派生表进行别名来实现
(SELECT * FROM Blah) AS A

例如,将派生表命名为A