WHERE子句中的多个OR条件 - 仅返回一条记录

时间:2014-08-22 17:50:20

标签: mysql case where

我有一个查询,根据4个条件为每个用户选择记录。我想基于heirachy为每个用户返回这些记录中的一个 - 例如:如果满足第一个条件(例如gemid = 123),则不包括该用户的任何其他记录。

更新根据Op De Cirkel的评论,我想排除多个subscribe, userid

查询:

SELECT subscribeid, userid
FROM subscribe 
WHERE (gemid=123) OR
      (grade=1 AND page IS NULL AND page2 IS NULL AND gemid IS NULL ) OR
      (grade=1 AND page ="page1" AND page2 IS NULL AND gemid IS NULL ) OR
      (grade=1 AND page ="page1" AND page2 = "page2" AND gemid IS NULL )

1 个答案:

答案 0 :(得分:0)

我能想到的最好的方法是计算WHERE语句的哪一部分符合条件,并将结果集包含在字段level中 - 并按userid, level排序。然后,我可以为结果集中的每个用户获取第一条记录。我无法弄清楚如何在不创建临时表的情况下为每个用户只包含这一条记录。

实际上,这不是任何解决方案,因为我也可以在php中处理它。

SELECT gemid, grade, page, page2, subscribeid, userid,
    CASE WHEN (gemid=123) THEN 1 ELSE
      CASE 
      WHEN (grade='1' AND page IS NULL AND page2 IS NULL AND gemid IS NULL ) THEN 2
          ELSE
              CASE 
              WHEN (grade='1' AND page ="page1" AND page2 IS NULL AND gemid IS NULL ) THEN 3 
              ELSE
                  CASE 
                  WHEN (grade='1' AND page ="page1" AND page2 = "page2" AND gemid IS NULL ) THEN 4 
                  ELSE
                      null
                  END
              END
          END
      END level
    FROM subscribe s
    WHERE (gemid=123) OR
          (grade='1' AND page IS NULL AND page2 IS NULL AND gemid IS NULL ) OR
          (grade='1' AND page ="page1" AND page2 IS NULL AND gemid IS NULL ) OR
          (grade='1' AND page ="page1" AND page2 = "page2" AND gemid IS NULL )
    ORDER BY userid, level