你在寻找这样的东西吗?
CREATE TABLE users
(
user_id int not null auto_increment primary key,
user_name varchar(32)
);
CREATE TABLE interests
(
interest_id int not null auto_increment primary key,
interest_name varchar(32)
);
CREATE TABLE user_interests
(
user_id int not null,
interest_id int not null,
foreign key (user_id) references users (user_id),
foreign key (interest_id) references interests (interest_id)
);
列出所有用户及其兴趣
SELECT user_id, interest_name
FROM user_interests ui JOIN interests i
ON ui.interest_id = i.interest_id
获取对“运动”有相同兴趣的用户列表
SELECT q.user_id, u.user_name
FROM
(
SELECT ui.user_id
FROM user_interests ui JOIN interests i
ON ui.interest_id = i.interest_id
GROUP BY user_id
HAVING MAX(i.interest_name = 'sports') = 1
) q JOIN users u
ON q.user_id = u.user_id
这是SQLFiddle演示