SQL field with multiple id's of other table

前端 未结 5 487
暗喜
暗喜 2021-01-04 21:27

Could someone give me an idea how to create this database structure. Here is an example:

Table \"countries\":
id, countryname
1, \"US\"
2, \"DE\"
3, \"FR\"
4         


        
5条回答
  •  萌比男神i
    2021-01-04 22:12

    What you're talking about is normalisation. You have a many-to-many structure, so you should create another table to link the two. You should never (ok, pretty much never) use delimited strings to store a list of values in a relational database.

    Here's an example of the setup:

    product_countries table
    
    productid | countryid
    ----------+-----------
    1         | 1
    1         | 2
    1         | 4
    2         | 2
    2         | 3
    2         | 4
    

    You can use a foreign key to each other table, then make them both into a composite primary key.

    You can then get a list of supported products for a country ID like this:

    SELECT * FROM products, product_countries
    WHERE products.id = product_countries.productid
    AND product_countries.countryid = $cid
    

提交回复
热议问题