SQL为所有用户获取重复记录

时间:2014-06-04 10:10:16

标签: sql

我有这些表

CREATE TABLE subject 
(
  id int auto_increment primary key, 
  name varchar(20)   
);

INSERT INTO subject
  (name)
VALUES
  ('subject 1'),('subject 2'), ('subject 3');

CREATE TABLE course 
(
  id int auto_increment primary key, 
  name varchar(20),
  subject_id int,
  FOREIGN KEY (subject_id) REFERENCES subject(id)
);

INSERT INTO course
  (subject_id, name)
VALUES
  (1, 'course 1'),(1, 'course 2'), (2, 'course 3'), (3, 'course 4');

CREATE TABLE user 
(
  id int auto_increment primary key, 
  name varchar(20),
  course_id int,
  FOREIGN KEY (course_id) REFERENCES course(id)
);

INSERT INTO user
  (course_id, name)
VALUES
  (1, 'User 1'),(1, 'User 1'), (2, 'User 3'), (3, 'User 4');

我想获得属于同一主题的课程的用户列表。

我运行此查询以获取列表

select u.name as user_name, s.name as subject_name from user u
inner join course c on u.course_id = c.id
inner join subject s on c.subject_id = s.id;

这是输出

USER_NAME   SUBJECT_NAME
User 1           subject 1
User 1           subject 1
User 3           subject 1
User 4           subject 2

预期输出

USER_NAME   SUBJECT_NAME
User 1           subject 1
User 1           subject 1

如何仅选择具有属于同一主题的课程的用户1?

fiddle link

1 个答案:

答案 0 :(得分:1)

要获得已注册超过1门课程的用户列表,请在小提琴中使用以下查询:

select u.name as user_name, s.name as subject_name from user u
inner join course c on u.course_id = c.id
inner join subject s on c.subject_id = s.id
having count(1) > 1;

要仅获取不同的用户和课程,请使用以下查询:

select distinct u.name as user_name, s.name as subject_name from user u
inner join course c on u.course_id = c.id
inner join subject s on c.subject_id = s.id;

编辑:我认为您需要获得以下查询可以使用的主题的不同用户的数量:

select  s.name as subject_name, count(distinct(u.name)) as no_of_users from user u
inner join course c on u.course_id = c.id
inner join subject s on c.subject_id = s.id
group by s.name;

仅使用count(u.name) as no_of_users您将获得实际计数而非明确计数。

再次编辑

要获得所需的输出,以下查询有效!

select tab_a.user_name, tab_a.subject_name from
(
   select u.name as user_name, s.name as subject_name from user u
   inner join course c on u.course_id = c.id
   inner join subject s on c.subject_id = s.id  
)tab_a
inner join
(
   select u.name as user_name, s.name as subject_name, count(1) reccount from user u
   inner join course c on u.course_id = c.id
   inner join subject s on c.subject_id = s.id
   group by u.name, s.name
) tab_b
on tab_a.user_name = tab_b.user_name
where tab_b.reccount >1