SQLize Online / PHPize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
CREATE TABLE customers( id INT (10) NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR (50) NOT NULL, city VARCHAR (50) NOT NULL ); CREATE TABLE orders( cus_id INT (10) NOT NULL, order_date DATETIME NOT NULL ); CREATE TABLE products( id INT (5) NOT NULL PRIMARY KEY, product_name VARCHAR(50) NOT NULL, product_price INT(10) NOT NULL ); CREATE TABLE ordered_items( id INT (10) NOT NULL PRIMARY KEY AUTO_INCREMENT, cus_id INT (10) NOT NULL, product_id INT(5) NOT NULL ); ALTER TABLE orders ADD CONSTRAINT customers_id_fr FOREIGN KEY ( cus_id ) REFERENCES customers ( id ); ALTER TABLE ordered_items ADD CONSTRAINT ordered_items_fr FOREIGN KEY ( cus_id ) REFERENCES customers ( id ); INSERT INTO customers (name, city) VALUES ("My Name", "New York"); INSERT INTO orders (cus_id, order_date) VALUES ("1", NOW()); INSERT INTO products (id, product_name, product_price) VALUES ("99", "My test product nr. 1", "20"); INSERT INTO products (id, product_name, product_price) VALUES ("98", "My test product nr. 2", "10"); INSERT INTO ordered_items (id, cus_id, product_id) VALUES ("1", "1", "99"); INSERT INTO ordered_items (id, cus_id, product_id) VALUES ("2", "1", "98"); SELECT name FROM customers INNER JOIN orders ON orders.cus_id = customers.id INNER JOIN ordered_items ON ordered_items.cus_id = orders.cus_id INNER JOIN products ON products.id = ordered_items.product_id; SELECT DISTINCT name FROM customers INNER JOIN orders ON orders.cus_id = customers.id INNER JOIN ordered_items ON ordered_items.cus_id = orders.cus_id INNER JOIN products ON products.id = ordered_items.product_id; SELECT name FROM customers WHERE EXISTS (SELECT 1 FROM ordered_items WHERE ordered_items.cus_id = customers.id )

Stuck with a problem? Got Error? Ask ChatGPT!

Copy Clear