1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| mysql> create table products ( id int not null auto_increment, name varchar(45) not null, primary key (id)) engine=InnoDB;
Query OK, 0 rows affected (0.22 sec)
mysql> create table orders ( id int not null auto_increment, primary key (id)) engine=InnoDB;
Query OK, 0 rows affected (0.39 sec)
mysql> create table order_products ( order_id int not null, product_id int not null, primary key (order_id, product_id)) engine=InnoDB;
Query OK, 0 rows affected (0.09 sec)
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| order_products |
| orders |
| products |
+----------------+
3 rows in set (0.05 sec)
mysql> insert into products values (1,'produit 1'),(2, 'produit 2'),(3, 'produit 3'),(4, 'produit 4'),(5, 'produit 5');
Query OK, 5 rows affected (0.14 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> insert into orders values (1),(2),(3);
Query OK, 3 rows affected (0.11 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> insert into order_products values (1,1),(1,2),(2,2),(2,3),(3,1),(3,4);
Query OK, 6 rows affected (0.06 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> select o.id as order_id, p.id as product_id, p.name as product_name from orders as o join order_products as op on (o.id=op.order_id) join products as p on (p.id=op.product_id) order by o.id,p.id;
+----------+------------+--------------+
| order_id | product_id | product_name |
+----------+------------+--------------+
| 1 | 1 | produit 1 |
| 1 | 2 | produit 2 |
| 2 | 2 | produit 2 |
| 2 | 3 | produit 3 |
| 3 | 1 | produit 1 |
| 3 | 4 | produit 4 |
+----------+------------+--------------+
6 rows in set (0.00 sec) |
Partager