sql >> Database >  >> RDS >> Mysql

voeg meerdere waarden toe in één kolom

U kunt geen geneste tabel maken. En waar u aan denkt, is geen goed idee om zo'n tafel te ontwerpen. Je zou twee tabellen moeten hebben (precies drie die de beschrijving bevatten als de categorie ). Een is voor het product en de tweede tabel bevat de categorie voor elk product . Een voorbeeldontwerp ziet er als volgt uit,

CREATE TABLE Product
(
    ProductID INT PRIMARY KEY,
    ProductName VARCHAR(50) UNIQUE
);

CREATE TABLE Category
(
    CategoryID INT PRIMARY KEY,
    CategoryName VARCHAR(50) UNIQUE
);

CREATE TABLE Product_Category
(
    RecordD INT AUTO_INCREMENT PRIMARY KEY,
    CategoryID INT,
    ProductID INT,
    CONSTRAINT tb_uq UNIQUE(CategoryID, ProductID)
);

en voorbeeldrecords invullen

INSERT Category VALUES (1, 'Fruit');
INSERT Category VALUES (2, 'Vegetable');

INSERT Product VALUES (1, 'Apple');
INSERT Product VALUES (2, 'Banana');
INSERT Product VALUES (3, 'Cabbage');
INSERT Product VALUES (4, 'Squash');
INSERT Product VALUES (5, 'Tomato');

INSERT Product_Category (CategoryID, ProductID) VALUES (1,1);
INSERT Product_Category (CategoryID, ProductID) VALUES (1,2);
INSERT Product_Category (CategoryID, ProductID) VALUES (2,3);
INSERT Product_Category (CategoryID, ProductID) VALUES (2,4);
INSERT Product_Category (CategoryID, ProductID) VALUES (1,5);
INSERT Product_Category (CategoryID, ProductID) VALUES (2,5);

voorbeeldvragen

-- NORMAL QUERY
SELECT  a.ProductName, c.CategoryName
FROM    Product a
        INNER JOIN Product_category b
          ON a.ProductID = b.ProductID
        INNER JOIN Category c
          ON b.CategoryID = c.CategoryID
ORDER BY ProductName;

-- If you want catgoryName to be comma separated
SELECT  a.ProductName, GROUP_CONCAT(c.CategoryName) CategoryList
FROM    Product a
        INNER JOIN Product_category b
          ON a.ProductID = b.ProductID
        INNER JOIN Category c
          ON b.CategoryID = c.CategoryID
GROUP BY ProductName
ORDER BY ProductName;


  1. Waar moet ik een externe sleutel bewaren?

  2. Fix "Rekenkundige overloopfout bij het converteren van IDENTITEIT naar gegevenstype ..." in SQL Server

  3. Waarom is mijn tafel meer dan 4x groter dan verwacht? (rijen*bytes/rij)

  4. ORA-38868