查询以获取公共值

时间:2011-08-17 05:08:21

标签: mysql sql

我有一张像

这样的表格
userId  classId 
1        1           
2        1          
3        1 
1        2 
2        2 
1        3 
2        4
3        5 

在上面,[1,2,3]分享等级1. [1,2]分享等级2,依此类推。

如果我在一个应该返回classId 1的查询中给出userId 1,2,3。

如果我给1和2,查询应返回2.

如果我给1,查询应返回3.

如何为此编写MySQL查询?

4 个答案:

答案 0 :(得分:1)

您需要的关系运算符是division,通常称为"the supplier who supplies all parts"

由于在给定class = 1时您不认为user = {1, 2}是有效结果,因此您应该查看exact division(即没有余数)。你还需要考虑结果应该是一个空的除数。

答案 1 :(得分:0)

这是用Postgresql测试的,但我很确定它在mysql下没有太多修改就可以工作。

表格设置

drop table classes;

create table classes (
    user_id     integer,
    class_id    integer
);

insert into classes values(1, 1);
insert into classes values(2, 1);
insert into classes values(3, 1);
insert into classes values(1, 2);
insert into classes values(2, 2);
insert into classes values(1, 3);
insert into classes values(2, 4);
insert into classes values(3, 5);

1,2,3

select max(class_id) from
(
  select class_id
  from classes
  where user_id = 1

  intersect

  select class_id
  from classes
  where user_id = 2

  intersect

  select class_id
  from classes
  where user_id = 3
) as foo;

1,2

select max(class_id) from
(
  select class_id
  from classes
  where user_id = 1

  intersect

  select class_id
  from classes
  where user_id = 2
) as foo;

1(可以简化,但出于对称原因,我更喜欢这样做)

select max(class_id) from
(
  select class_id
  from classes
  where user_id = 1
) as foo;

答案 2 :(得分:0)

您可以使用这样的查询(对于用户1,2,3) -

SELECT t1.classId FROM (SELECT * FROM users_classes WHERE userId = 1) t1 -- for userId = 1
  JOIN (SELECT * FROM users_classes WHERE userId = 2) t2 ON t1.classId = t2.classId -- for userId = 2
  JOIN (SELECT * FROM users_classes WHERE userId = 3) t3 ON t1.classId = t3.classId -- for userId = 3

对于用户1,2 -

SELECT t1.classId FROM (SELECT * FROM users_classes WHERE userId = 1) t1 -- for userId = 1
  JOIN (SELECT * FROM users_classes WHERE userId = 2) t2 ON t1.classId = t2.classId -- for userId = 2

这些查询将输出所有可能的classId,以获得一个classId,您可以添加LIMIT或聚合函数。

答案 3 :(得分:-1)

    Try this


      SELECT DISTINCT (
        classId
        )
        FROM `data`
        WHERE userid =1
        OR userid =2 or classid = 3            
        LIMIT 0 , 1

        SELECT DISTINCT (
        classId
        )
        FROM `data`
        WHERE userid =1
        OR userid =2            
        LIMIT 1 , 1

   SELECT DISTINCT (
        classId
        )
        FROM `data`
        WHERE userid =1     

        LIMIT 2 , 1