对更多表进行 UNION 时创建唯一 ID 的建议
我有一个这样的视图
CREATE VIEW PEOPLE
AS
SELECT CustomerId, CustomerName FROM Customers
UNION ALL
SELECT EmployeeId, EmployeeName FROM Employees
UNION ALL
SELECT FriendId, FriendName From Friends
,现在我需要为该视图添加唯一的 ID,因为我当然可以有一个 CustomerId = 15
和一个 EmployeeID = 15
所以技巧我正在做的是以下
SELECT
CAST('1' + CAST(CustomerId AS VARCHAR(30)) AS INT) as UniqueCustomerId,
CustomerId, CustomerName FROM Customers
UNION ALL
SELECT
CAST('2' + CAST(EmployeeId AS VARCHAR(30)) AS INT) as UniqueEmployeeId,
EmployeeId, EmployeeName FROM Employees
UNION ALL
SELECT
CAST('3' + CAST(FriendId AS VARCHAR(30)) AS INT) as UniqueFriendId,
FriendId, FriendName From Friends
无论如何,由于我有很多记录,所以转换为 varchar(30)
并返回 int
是一项开销。
你能建议一个更好的方法吗?
I have a view made like this
CREATE VIEW PEOPLE
AS
SELECT CustomerId, CustomerName FROM Customers
UNION ALL
SELECT EmployeeId, EmployeeName FROM Employees
UNION ALL
SELECT FriendId, FriendName From Friends
now I need to add unique ID for the view, because of course i can have a CustomerId = 15
and an EmployeeID = 15
So the trick I am doing is the following
SELECT
CAST('1' + CAST(CustomerId AS VARCHAR(30)) AS INT) as UniqueCustomerId,
CustomerId, CustomerName FROM Customers
UNION ALL
SELECT
CAST('2' + CAST(EmployeeId AS VARCHAR(30)) AS INT) as UniqueEmployeeId,
EmployeeId, EmployeeName FROM Employees
UNION ALL
SELECT
CAST('3' + CAST(FriendId AS VARCHAR(30)) AS INT) as UniqueFriendId,
FriendId, FriendName From Friends
Anyway this casting to varchar(30)
and back to int
is an overhead since I have many records.
Could you suggest a better approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你必须有一个 id,只需做数学计算:
If you've got to have a single id, just do math:
我更喜欢这种方法,因为它仍然可以使用 CustomerID、EmployeeID 和 FriendID 上的索引
I prefer this approach as it can still use indexes on the CustomerID, EmployeeID, and FriendID
干净且可读性好,我在 Postgres 中使用它。
Clean and well readable, I use this in Postgres.
这应该可以正常工作:
This should work fine: