我需要缩短这个查询,虽然我擅长SQL,但我还在学习.
SELECT 'doejoh', DATETIME, [Recipient-Address], [Message-Subject], [Sender-Address] FROM dbo.Logs WHERE LEFT([Recipient-Address], 6) IN ('doejoh') UNION ALL SELECT 'doejoh', DATETIME, [Recipient-Address], [Message-Subject], [Sender-Address] FROM dbo.Logs WHERE LEFT([Recipient-Address], 10) IN ('john.doe@g') UNION ALL SELECT 'doejoh', DATETIME, [Recipient-Address], [Message-Subject], [Sender-Address] FROM dbo.Logs WHERE LEFT([Sender-Address], 6) IN ('doejoh') UNION ALL SELECT 'doejoh', DATETIME, [Recipient-Address], [Message-Subject], [Sender-Address] FROM dbo.Logs WHERE LEFT([Sender-Address], 10) IN ('john.doe@g') ORDER BY DateTime
我必须使用这个联合,因为在同一个表中,每个用户及其电子邮件地址有4种不同的可能性.话虽这么说,我有30个用户,所以在整个查询中30x4将是120个组.第一列必须是用户名的原因是因为我在Crystal Report中使用该列.
我只是想为我的查询创建一些逻辑来缩短它,同时将每个用户"分配"到适当的第一列.
编辑添加
虽然这会缩短我的查询,但我仍然需要有30个工会:
SELECT 'doejoh', DATETIME, [Recipient-Address], [Message-Subject], [Sender-Address] FROM dbo.Logs WHERE LEFT([Recipient-Address], 6) IN ('doejoh') OR LEFT([Recipient-Address], 10) IN ('john.doe@g') OR LEFT([Sender-Address], 6) IN ('doejoh') OR LEFT([Sender-Address], 10) IN ('john.doe@g') ORDER BY DateTime
因为下一个用户将与前一个用户联合:
UNION ALL SELECT 'doejan', DATETIME, [Recipient-Address], [Message-Subject], [Sender-Address] FROM dbo.Logs WHERE LEFT([Recipient-Address], 6) IN ('doejan') OR LEFT([Recipient-Address], 10) IN ('jane.doe@g') OR LEFT([Sender-Address], 6) IN ('doejan') OR LEFT([Sender-Address], 10) IN ('jan.doe@g')
等等......任何更短的方式?
您应该将查询重写为:
SELECT 'doejoh', DATETIME, [Recipient-Address], [Message-Subject], [Sender-Address] FROM dbo.Logs WHERE LEFT([Recipient-Address], 6) IN ('doejoh') OR LEFT([Recipient-Address], 10) IN ('john.doe@g') OR LEFT([Sender-Address], 6) IN ('doejoh') OR LEFT([Sender-Address], 10) IN ('john.doe@g') ORDER BY DateTime
我认为,在选择方面应该是相同的,只是更快,更容易理解.
渣