最后一块拼图已被省略,作为读者的练习......
DROP TABLE IF EXISTS users;
CREATE TABLE users
(user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,user_name VARCHAR(20) NOT NULL UNIQUE
,user_email VARCHAR(12) NOT NULL
);
INSERT INTO users VALUES
(1 ,'john','ex0@email'),
(2 ,'nathel','ex1@email'),
(3 ,'bob','ex2@email');
DROP TABLE IF EXISTS product_user;
CREATE TABLE product_user
(product_id INT NOT NULL
,user_id INT NOT NULL
,PRIMARY KEY (product_id,user_id)
);
INSERT INTO product_user VALUES
(1, 1),(2 ,1),(1 ,2),(1,3),(3,3);
DROP TABLE IF EXISTS products;
CREATE TABLE products
(product_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,product_name VARCHAR(12) NOT NULL UNIQUE);
INSERT INTO products VALUES (1 ,'Platinum'),(2,'Gold'),(3,'Steel');
SELECT *
FROM product_user x
LEFT
JOIN product_user y
ON y.user_id = x.user_id
AND y.product_id <> x.product_id
WHERE x.product_id =1;
+------------+---------+------------+---------+
| product_id | user_id | product_id | user_id |
+------------+---------+------------+---------+
| 1 | 1 | 2 | 1 |
| 1 | 2 | NULL | NULL |
| 1 | 3 | 3 | 3 |
+------------+---------+------------+---------+
SELECT *
FROM product_user x
LEFT
JOIN product_user y
ON y.user_id = x.user_id
AND y.product_id <> x.product_id
JOIN users u
ON u.user_id = x.user_id
JOIN products p
ON p.product_id = x.product_id
WHERE p.product_name = 'Platinum';
+------------+---------+------------+---------+---------+-----------+------------+------------+--------------+
| product_id | user_id | product_id | user_id | user_id | user_name | user_email | product_id | product_name |
+------------+---------+------------+---------+---------+-----------+------------+------------+--------------+
| 1 | 1 | 2 | 1 | 1 | john | ex0@email | 1 | Platinum |
| 1 | 2 | NULL | NULL | 2 | nathel | ex1@email | 1 | Platinum |
| 1 | 3 | 3 | 3 | 3 | bob | ex2@email | 1 | Platinum |
+------------+---------+------------+---------+---------+-----------+------------+------------+--------------+