sql >> Databáze >  >> RDS >> Mysql

Jak vytvořit tabulky se vztahem N:M v MySQL?

Many-to-one (produkty mohou mít pouze jeden obchod)

create table store(
    id int unsigned not null auto_increment,
    store_name varchar(30) not null,
    primary key(id)
);

Query OK, 0 rows affected (0.02 sec)

create table product(
    id int unsigned not null auto_increment,
    store_id int unsigned not null,
    product_name varchar(30) not null,
    price float not null,
    primary key(id),
    constraint product_store foreign key (store_id) references store(id)
);

Query OK, 0 rows affected (0.02 sec)

Many-to-many (produkty mohou být v mnoha obchodech)

create table store(
    id int unsigned not null auto_increment,
    store_name varchar(30) not null,
    primary key(id)
);

Query OK, 0 rows affected (0.04 sec)

create table product(
    id int unsigned not null auto_increment,
    store_id int unsigned not null,
    product_name varchar(30) not null,
    price float not null,
    primary key(id)
);

Query OK, 0 rows affected (0.01 sec)

create table product_store (
    product_id int unsigned not null,
    store_id int unsigned not null,
    CONSTRAINT product_store_store foreign key (store_id) references store(id),
    CONSTRAINT product_store_product foreign key (product_id) references product(id),
    CONSTRAINT product_store_unique UNIQUE (product_id, store_id)
)

Query OK, 0 rows affected (0.02 sec)


  1. Přístup odepřen pro uživatele 'root'@'localhost' (pomocí hesla:YES )

  2. Uložit pole PHP do MySQL?

  3. mysql pivoting - jak mohu načíst data ze stejné tabulky do různých sloupců?

  4. Odečtěte mikrosekundy od hodnoty Datetime v MariaDB