Theme
Primary Color
Lesson 21

Constraint – Foreign Key – Many To Many

الأوامر التي تم كتابتها في الدرس

/* Create Table shops*/
CREATE TABLE shops (
	shop_id INT NOT NULL PRIMARY KEY,
    name varchar(255)
) ENGINE = INNODB;

/* Create Table shop_members */
CREATE TABLE shop_members (
	client INT NOT NULL,
    shop INT NOT NULL,
    PRIMARY KEY(client, shop),
    CONSTRAINT cons_clients
    	FOREIGN KEY (client) REFERENCES clients (id)
    	ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT cons_shop
    	FOREIGN KEY (shop) REFERENCES shops (shop_id)
    	ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = INNODB;

/* Select From Clients And Join Shop Members */
SELECT
	*
FROM
	clients
JOIN
	shopmember
ON
	clients.id = shopmember.client
WHERE
	shopmember.shop = 1;

/* Select From Shops And Join Shop Members */
SELECT
	*
FROM
	shops
JOIN
	shopmember
ON
	shops.shop_id = shopmember.shop
WHERE
	shopmember.client = 1;