Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

Bagaimana cara membuat tabel dengan hubungan N:M di MySQL?

Many-to-one (produk hanya dapat memiliki satu toko)

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 (produk bisa di banyak toko)

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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Bagaimana cara menyimpan desimal di MySQL?

  2. Haruskah MySQL mengatur zona waktunya ke UTC?

  3. Gagal menemukan direktori data yang valid. Instalasi biner generik MySQL

  4. optimalkan kueri penghitungan mysql

  5. Bagaimana cara memetakan kolom MySQL char(n) ke variabel instan menggunakan anotasi JPA/Hibernate?