mysql - 我如何制作条件 WHERE 子句(或替代方式)

标签 mysql sql

我尝试计算所有处于“无效”状态的行。这可以是不同的状态、字段内容,而且,这是我的问题,当一个状态可以并且两个字段不相同时,它仍然会被视为无效

SELECT count(status) 
    FROM db.table 
    WHERE name LIKE  '".$needle."' AND 
    (
        (
            (                           
            status LIKE 'NOT%OK' OR         /* listing all status that we want to catch     */
            status LIKE 'XY' OR
            status LIKE 'XYZ' OR 
            unauth_change IS NOT NULL       /* also those where unauth_change is not empty  */
            ) OR 
            (
            status LIKE 'OK' AND            /* if the status is "ok" though and the     */
            planned_place = actual_place    /* planned and actual place on are not same     */
            )                               /* then still count it                          */
        )
        AND
        override NOT LIKE 'Y'               /* overridden items are discarded anyway        */      
    )  LIMIT 1;

我尝试了 IF 函数但失败了,我什至不确定它是否会按照我的预期工作。下面的查询是最新的测试,我想说“(‘状态’无效”或“状态有效,但计划和实际不一样”)和“其余条款”。 我也尝试过 IF(status ='ok',planned_place =actual_place,1) 但老实说,我是在黑暗中钓鱼。

示例行和预期结果

name| status |  unauth_change | planned_place | actual_place | override | COUNT?|
---------------------------------------------------------------------------------------
abc | notok  |                | A             | A            | N        | yes
cde | xy     |                | A             | A            | N        | yes
efg | xyz    |                | A             | A            | Y        | no (override)
hij | ok     | blablabla      | A             | A            | N        | yes (unauth)
lmn | ok     |                | A             | B            | N        | yes (planned/actual)
opq | ok     |                | A             | A            | N        | no

列表项

最佳答案

尝试这样的事情:

SELECT COUNT(name)
FROM tableNameHere
WHERE name LIKE searchTermHere
AND (status NOT LIKE 'ok'
OR unauth_change IS NOT NULL
OR planned_place != actual_place)
AND override LIKE 'N'

关于mysql - 我如何制作条件 WHERE 子句(或替代方式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56687169/

相关文章:

php - 查找时间戳范围在另一个时间戳范围内的所有行

mysql - 在 J2EE/MySQL 后端使用 <input type=file/>

mysql - 刷新和锁定 RDS Mysql 数据库中的表所需的权限

php - 计算帖子的平均评分

MySQL比较不同格式的时间

mysql - MySQL整数字段匹配字符串是怎么回事?

mysql - 我正在尝试删除 MySQL 数据库,但它在控制台中显示错误

sql - 从每组中选择随机值,SQL

sql - SQL查询未返回正确的日期范围

mysql - WHERE 子句后跟 JOIN