找到导致sql返回的where子句的一部分

时间:2015-03-07 03:30:26

标签: mysql sql where

我有一个类似的mysql查询,

SELECT USER
FROM   users
WHERE  user_name = someUserName
        OR location = someLocation
        OR deleted = 1 
LIMIT 1

我正在试图找出哪个案例导致用户被选中。这可能吗?

3 个答案:

答案 0 :(得分:0)

通过选择过滤栏,您可以找到哪个有效。

SELECT USER,
       user_name,
       location,
       deleted,
       CASE
         WHEN user_name = someUserName
              AND location <> someLocation
              AND deleted <> 1 THEN 'User_name'
         WHEN location = someLocation
              AND user_name <> someUserName
              AND deleted <> 1 THEN 'location'
         WHEN location <> someLocation
              AND user_name <> someUserName
              AND deleted = 1 THEN 'deleted'
         WHEN user_name = someUserName
              AND location = someLocation
              AND deleted <> 1 THEN 'User_name,location'
         WHEN user_name = someUserName
              AND location <> someLocation
              AND deleted = 1 THEN 'User_name,deleted'
         WHEN user_name <> someUserName
              AND location = someLocation
              AND deleted = 1 THEN 'location,deleted'
         WHEN user_name = someUserName
              AND location = someLocation
              AND deleted = 1 THEN 'ALL'
       END AS Filer_Column
FROM   users
WHERE  user_name = someUserName
        OR location = someLocation
        OR deleted = 1 
LIMIT 1

Limit order by {{1}} {{1}}对我没有任何意义。最好添加您想要限制结果集的顺序

答案 1 :(得分:0)

如果您想表明满足所有条件(如果有多个条件),您可以像这样解决问题:

select user, group_concat(condition_met) as conditions_met
  from (select user, 'A' as condition_met
          from users
         where user_name = someusername
        union all
        select user, 'B'
          from users
         where location = someLocation
        union all
        select user, 'C'
          from users
         where deleted = 1) x
 group by user

这在功能上应该是等效的:

select user,
       sum(user_name = someusername) as cond_a,
       sum(location = someLocation) as cond_b,
       sum(deleted = 1)) as as cond_c
  from users
 where user_name = someusername
    or location = somelocation
    or deleted = 1
 group by user

答案 2 :(得分:0)

有时候我会调试一些东西,我希望能够回答相同类型的问题。显然,你可以注释掉部分查询并以这种方式运行它。如果您不确定某个表达式或空值,或者您只是想确认您的理智,那么您可能只是尝试一个案例表达式。

SELECT
    user
    case when user_name = someUserName then 'true' else 'false' end as Condition1,
    case when location  = someLocation then 'true' else 'false' end as Condition2,
    case when deleted   = 1 then 'true' else 'false' end as Condition 3
FROM users
WHERE
        user_name = someUserName
    OR  location = someLocation
    OR  deleted = 1 
LIMIT 1