miércoles, 7 de mayo de 2014

Selection query using comma vs cross join in SQL

CREATE TABLE [dbo].[master](
[id] [int] IDENTITY(1,1) NOT NULL,
[master] [varchar](50) NOT NULL,
 CONSTRAINT [PK_master] PRIMARY KEY CLUSTERED 
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[detail](
[id] [int] IDENTITY(1,1) NOT NULL,
[idmaster] [int] NOT NULL,
[detail] [varchar](50) NOT NULL,
 CONSTRAINT [PK_detail] PRIMARY KEY CLUSTERED 
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[detail]  WITH CHECK ADD  CONSTRAINT [FK_detail_master] FOREIGN KEY([idmaster]) REFERENCES [dbo].[master] ([id])
GO
ALTER TABLE [dbo].[detail] CHECK CONSTRAINT [FK_detail_master]
GO

INSERT INTO [master] VALUES ('MASTER-1')
INSERT INTO [master] VALUES ('MASTER-2')
INSERT INTO [detail] VALUES (1,'DETAIL-1')
INSERT INTO [detail] VALUES (2,'DETAIL-2')
INSERT INTO [detail] VALUES (3,'DETAIL-3')

SELECT * FROM [master], [detail]
SELECT * FROM [master] CROSS JOIN [detail]
SELECT * FROM [master] m FULL JOIN [detail] d ON m.id = d.idmaster 
SELECT * FROM [master] m LEFT JOIN [detail] d ON m.id = d.idmaster
SELECT * FROM [master] m RIGHT JOIN [detail] d ON m.id = d.idmaster
SELECT * FROM [master] m INNER JOIN [detail] d ON m.id = d.idmaster


|id|master  |id|idmaster|detail  |
|--|--------|--|--------|--------|
|1 |MASTER-1|1 |1       |DETAIL-1|
|2 |MASTER-2|1 |1       |DETAIL-1|
|1 |MASTER-1|2 |2       |DETAIL-2|
|2 |MASTER-2|2 |2       |DETAIL-2|