Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Вариант 2 с 3 таблицами
- use Test1
- GO
- CREATE TABLE Products3 (
- Id INT PRIMARY KEY IDENTITY,
- Product NVARCHAR(20) NOT NULL,
- )
- GO
- CREATE TABLE Categories3 (
- Id INT PRIMARY KEY IDENTITY,
- Category NVARCHAR(20) NOT NULL,
- )
- GO
- CREATE TABLE ProdsAndCats3 (
- Id INT PRIMARY KEY IDENTITY,
- ProductId INT NOT NULL,
- CategoryId INT NOT NULL,
- FOREIGN KEY (ProductId) REFERENCES Products3 (Id),
- FOREIGN KEY (CategoryId) REFERENCES Categories3(Id)
- )
- GO
- INSERT INTO Categories3 (Category)
- VALUES ('Gadgets'),
- ('Drinks'),
- ('Medicines'),
- ('Food'),
- ('Smartphones')
- GO
- INSERT Into Products3 (Product)
- VALUES ('Galaxy S21'),
- ('Coca Cola'),
- ('Nokia 3310'),
- ('Huawie FreeBuds 5i'),
- ('Парацетамол'),
- ('Milk 1L'),
- ('XBox One X')
- GO
- INSERT INTO ProdsAndCats3 (ProductId, CategoryId)
- VALUES (1,1),
- (2,4),
- (3,1),
- (4,1),
- (5,3),
- (6,4),
- (1,5)
- GO
- SELECT p.Product as product, c.Category as category
- FROM Products3 AS p
- LEFT JOIN ProdsAndCats3 AS pc ON pc.ProductId =p.Id
- LEFT JOIN Categories3 AS c ON c.Id = pc.CategoryId
- GO
Add Comment
Please, Sign In to add comment