Not to duplicate what's already been posted, but...
--
-- Working MySQL implementation of a "user compatibility" schema.
--
DROP TABLE IF EXISTS favourite;
DROP TABLE IF EXISTS artist;
DROP TABLE IF EXISTS users;
CREATE TABLE users (
user_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(32),
PRIMARY KEY (user_id)
);
CREATE TABLE artist (
artist_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(32),
PRIMARY KEY (artist_id)
);
CREATE TABLE favourite (
favourite_id INT NOT NULL AUTO_INCREMENT,
user_id INT NOT NULL,
artist_id INT NOT NULL,
UNIQUE (user_id, artist_id),
PRIMARY KEY (favourite_id),
FOREIGN KEY (user_id) REFERENCES users (user_id) ON DELETE CASCADE,
FOREIGN KEY (artist_id) REFERENCES artist (artist_id) ON DELETE CASCADE
);
INSERT INTO users
(name)
VALUES
("Alice"),
("Bob"),
("Carol"),
("Dave")
;
INSERT INTO artist
(name)
VALUES
("Jewel"),
("Sarah McLachlan"),
("Britney Spears"),
("David Bowie"),
("The Doors")
;
INSERT INTO favourite
(user_id, artist_id)
VALUES
(
(SELECT user_id FROM users WHERE name = "Alice"),
(SELECT artist_id FROM artist WHERE name = "Jewel")
),
(
(SELECT user_id FROM users WHERE name = "Alice"),
(SELECT artist_id FROM artist WHERE name = "Sarah McLachlan")
),
(
(SELECT user_id FROM users WHERE name = "Bob"),
(SELECT artist_id FROM artist WHERE name = "Jewel")
),
(
(SELECT user_id FROM users WHERE name = "Bob"),
(SELECT artist_id FROM artist WHERE name = "Sarah McLachlan")
),
(
(SELECT user_id FROM users WHERE name = "Bob"),
(SELECT artist_id FROM artist WHERE name = "Britney Spears")
),
(
(SELECT user_id FROM users WHERE name = "Bob"),
(SELECT artist_id FROM artist WHERE name = "David Bowie")
),
(
(SELECT user_id FROM users WHERE name = "Carol"),
(SELECT artist_id FROM artist WHERE name = "David Bowie")
),
(
(SELECT user_id FROM users WHERE name = "Carol"),
(SELECT artist_id FROM artist WHERE name = "The Doors")
),
(
(SELECT user_id FROM users WHERE name = "Dave"),
(SELECT artist_id FROM artist WHERE name = "Jewel")
),
(
(SELECT user_id FROM users WHERE name = "Dave"),
(SELECT artist_id FROM artist WHERE name = "The Doors")
)
;
SELECT
t0.user_id myuser,
t1.user_id friend,
COUNT(*)
FROM favourite t0
JOIN favourite t1 ON t1.artist_id = t0.artist_id
WHERE t0.user_id != t1.user_id
GROUP BY t0.user_id, t1.user_id;
--
-- The same thing, but returning names!
--
SELECT
t0u.name myuser,
t1u.name friend,
COUNT(*)
FROM favourite t0
JOIN favourite t1 ON t1.artist_id = t0.artist_id
JOIN users t0u ON t0u.user_id = t0.user_id
JOIN users t1u ON t1u.user_id = t1.user_id
WHERE t0.user_id != t1.user_id
GROUP BY t0.user_id, t1.user_id;
Good luck!