Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suggestions for creating a Unique ID when doing a UNION of more tables

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?

like image 845
LaBracca Avatar asked Sep 06 '25 05:09

LaBracca


1 Answers

If you've got to have a single id, just do math:

SELECT  1000000 + CustomerID AS UniqueCustomerId
      , CustomerId
      , CustomerName
FROM    Customers
UNION ALL
SELECT  2000000 + EmployeeId AS UniqueEmployeeId
      , EmployeeId
      , EmployeeName
FROM    Employees
UNION ALL
SELECT  3000000 + FriendId AS UniqueFriendId
      , FriendId
      , FriendName
FROM    Friends 
like image 114
Stuart Ainsworth Avatar answered Sep 09 '25 15:09

Stuart Ainsworth