选择基于多个条件

时间:2013-08-08 13:01:21

标签: mysql

如果我们有两个这样的表

CREATE TABLE ta(`ID` int, `name` char(10));
INSERT INTO ta (`ID`, `name`)
VALUES
    (1, 'A'),
    (2, 'A'),
    (3, 'B'),
    (4, 'C'),
    (5, 'B');

CREATE TABLE yourtable(`ID` int, `Val` int);
INSERT INTO yourtable (`ID`, `Val`)
VALUES
    (1, 10),
    (1, 20),
    (1, 30),
    (1, 30),
    (2, 10),
    (2, 20),
    (3, 20),
    (3, 20),
    (4, 10),
    (4, 20),    
    (5, 10),
    (5, 20),
    (5, 30);

而且,我需要使用两个表将值name分组。并且,对于条件val = 10或val = 30,它工作正常。 http://sqlfiddle.com/#!2/9c099/1

select name, count(distinct t1.id)
from yourtable as t1, ta
where t1.id=ta.id
AND (val=10 OR val=30)
group by name

但是,对于条件(val = 10 AND val!= 30)我该如何查询? 为此,输出应

   Count
A  1
B  0
C  1

以下是一个例子:以name = A为例,这里我们得到ID = 1,2。所以,现在在yourtable表中我们有5行ID = 1,2。对于ID = 1,val = 10,20,20。对于ID = 2,val = 10,20。这里只有ID = 2满足(val = 10 AND val!= 30)因此,对于name = A count = 1

3 个答案:

答案 0 :(得分:0)

SELECT ta.name
     , COUNT(DISTINCT t2.val)
  FROM yourtable t1 
  LEFT
  JOIN yourtable t2
    ON t2.id = t1.id 
   AND t2.val IN (30) -- <-- things to exclude
  LEFT
  JOIN ta 
    ON ta.id = t1.id 
 WHERE t1.val IN (10) -- <-- things to include
 GROUP
    BY name;

NAME COUNT(T2.VAL)
A    1
B    1
C    0

http://sqlfiddle.com/#!2/9c099/169

答案 1 :(得分:0)

您希望yourtable上的子查询确定ID是否满足条件,并将其加入ta

select name, SUM(Satisfies)
from ta, (
    SELECT distinct ID, CASE WHEN ID NOT IN (
        SELECT ID FROM yourtable
        WHERE Val = 30 )
    AND ID IN (
        SELECT ID FROM yourtable
        WHERE Val = 10 ) THEN 1 ELSE 0 END Satisfies
    FROM yourtable
) t1
WHERE t1.id=ta.id
group by name

SQL Fiddle

答案 2 :(得分:0)

不太好但是工作:

SELECT name, max(occ) occurencies
  FROM (SELECT name, count(distinct t1.id) as occ
          FROM yourtable as t1, ta
         WHERE t1.id=ta.id
           AND val=10 
           AND NOT EXISTS (SELECT name 
                             FROM yourtable as t2 
                            WHERE t2.id=ta.id AND t2.val=30)
        GROUP BY name
        UNION
        SELECT name, 0 as occ
          FROM yourtable as t1, ta
         WHERE t1.id=ta.id
           AND val=10 
           AND EXISTS (SELECT name 
                         FROM yourtable as t2 
                        WHERE t2.id=ta.id AND t2.val=30)) as base
 GROUP BY name;

退房:http://sqlfiddle.com/#!2/9c099/192

p.s。:稍微好一些:

 SELECT ta.name, COALESCE (occ, 0)
   FROM ta
   LEFT JOIN (SELECT name, count(distinct t1.id) as occ
                FROM yourtable as t1, ta
               WHERE t1.id=ta.id
                 AND val=10 
                 AND NOT EXISTS (SELECT name 
                                   FROM yourtable as t2 
                                  WHERE t2.id=ta.id 
                                    AND t2.val=30)
               GROUP BY name) AS base ON (base.name = ta.name)
  GROUP BY name;    

http://sqlfiddle.com/#!2/9c099/212

:)