mysql根据计数选择where where condition

时间:2014-09-19 13:53:04

标签: mysql

我的查询看起来像这样:

SELECT * FROM `bas_HCCxmlSettings` 
WHERE `waarde3` = 'Oke' 
    OR `waarde4` = 'Oke' 
    AND `config` = 'XMLserver'

现在我想添加特殊条件,如果waarde2 != 0的条件是waarde2 = 'int'其他waarde2 = 'ext'

这是我试过的:

尝试1:

SELECT * FROM `bas_HCCxmlSettings` 
WHERE `waarde3` = 'Oke'
    OR `waarde4` = 'Oke' 
    AND `config` = 'XMLserver' 
    AND `waarde2`= 
    (
        (
            SELECT count(*) 
            FROM `bas_HCCxmlSettings` 
            WHERE `config` = 'XMLserver' AND`waarde2`= 'int' AND 
                (`waarde3` = 'Oke' 
                    OR `waarde4` = 'Oke'
                )

        ) > 0
        ,'int'
        ,'ext'
    )

试试2:

if (SELECT count(*) FROM `bas_HCCxmlSettings` WHERE `waarde2`= 'int' AND (`waarde4` = 'Oke' OR `waarde3`= 'Oke')) > 0 
   THEN
       SELECT count(*) FROM `bas_HCCxmlSettings` WHERE `waarde2`= 'int' AND (`waarde4` = 'Oke' OR `waarde3`= 'Oke')
else
       SELECT count(*) FROM `bas_HCCxmlSettings` WHERE `waarde2`= 'ext' AND (`waarde4` = 'Oke' OR `waarde3`= 'Oke')
   END

出了什么问题?

我的查询主要查询的标准中的一些说明

选择标准必须是: 1. config ='XMLserver' 2. Waarde3或waarde4或两者都是'Oke'

查询没有waard2的标准是:

SELECT * FROM `bas_HCCxmlSettings` 
WHERE `config` = 'XMLserver' 
   AND`waarde2`= 'int' 
   AND (
         `waarde3` = 'Oke' 
          OR 
          `waarde4` = 'Oke'
       )

为了遏制waarde2的价值,我的选择要求是:

  1. config ='XMLserver'
  2. waarde2 = int
  3. Waarde3或waarde4或两者必须是'Oke'
  4. 计数查询将是:

    SELECT count(*) FROM `bas_HCCxmlSettings` 
    WHERE `config` = 'XMLserver' 
       AND`waarde2`= 'int' 
       AND (
             `waarde3` = 'Oke' 
             OR 
             `waarde4` = 'Oke'
           )
    

    如果此选择的计数为0,则waarde = ext 如果此选择的计数较大,那么0 waarde = int

2 个答案:

答案 0 :(得分:0)

我终于找到了解决方案,它是:

SELECT * FROM `bas_HCCxmlSettings` 
WHERE `config` = 'XMLserver' 
AND (
    `waarde3` = 'Oke'
    OR
    `waarde4` = 'Oke'
    )
    AND
    CASE 
    (
        select COUNT(*) from bas_HCCxmlSettings
        where 
        `config` ='XMLserver'
        AND
        `waarde2` = 'int'
        AND
        (
            `waarde3` = 'Oke'
            OR
            `waarde4` = 'Oke'
            )
        )
        WHEN 0 
        THEN `waarde2` = 'ext'
        ELSE `waarde2` = 'int'
        END

答案 1 :(得分:-2)

SELECT * FROM `bas_HCCxmlSettings` 
WHERE `waarde3` = 'Oke' 
OR `waarde4` = 'Oke' 
AND `config` = 'XMLserver'
AND waarde2 = (CASE COUNT(waarde2)
               WHEN 0 THEN 'ext' 
               ELSE 'INT' 
               END)

告诉我它是否有效!!!!