technologist02

SQL query Product version2

Dec 3rd, 2023 (edited)
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.08 KB | None | 0 0
  1. -- Вариант 2 с 3 таблицами
  2. use Test1
  3. GO
  4.  
  5. CREATE TABLE Products3 (
  6.     Id INT PRIMARY KEY IDENTITY,
  7.     Product NVARCHAR(20) NOT NULL,
  8. )
  9. GO
  10.  
  11. CREATE TABLE Categories3 (
  12.     Id INT PRIMARY KEY IDENTITY,
  13.     Category NVARCHAR(20) NOT NULL,
  14. )
  15. GO
  16.  
  17. CREATE TABLE ProdsAndCats3 (
  18.     Id INT PRIMARY KEY IDENTITY,
  19.     ProductId INT NOT NULL,
  20.     CategoryId INT NOT NULL,
  21.     FOREIGN KEY (ProductId)  REFERENCES Products3 (Id),
  22.     FOREIGN KEY (CategoryId) REFERENCES Categories3(Id)
  23.  
  24. )
  25. GO
  26.  
  27. INSERT INTO Categories3 (Category)
  28. VALUES ('Gadgets'),
  29. ('Drinks'),
  30. ('Medicines'),
  31. ('Food'),
  32. ('Smartphones')
  33. GO
  34.  
  35. INSERT Into Products3 (Product)
  36. VALUES ('Galaxy S21'),
  37. ('Coca Cola'),
  38. ('Nokia 3310'),
  39. ('Huawie FreeBuds 5i'),
  40. ('Парацетамол'),
  41. ('Milk 1L'),
  42. ('XBox One X')
  43. GO
  44.  
  45. INSERT INTO ProdsAndCats3 (ProductId, CategoryId)
  46. VALUES (1,1),
  47. (2,4),
  48. (3,1),
  49. (4,1),
  50. (5,3),
  51. (6,4),
  52. (1,5)
  53. GO
  54.  
  55.  
  56. SELECT p.Product as product, c.Category as category
  57.   FROM Products3 AS p
  58.   LEFT JOIN ProdsAndCats3 AS pc ON pc.ProductId =p.Id
  59.   LEFT JOIN Categories3 AS c ON c.Id = pc.CategoryId
  60.  
  61. GO
Add Comment
Please, Sign In to add comment