0

我正在尝试为 mysql 编写一个查询,(Search Module)因为要在同一个表中执行选择操作而遇到困难。

我的查询:

(SELECT * FROM user WHERE `user_name` like '%TOM%' OR `user_name` like '%AN%' 
and `login_datetime` BETWEEN '2013-01-01 00:00:00' and '2013-02-31 23:59:59')
    OR
(SELECT * FROM user WHERE `user_name` like '%PHP%' OR `user_name` like '%BA%' 
and `login_datetime` BETWEEN '2013-02-01 00:00:00' and '2013-03-31 23:59:59')
    AND
(SELECT * FROM user WHERE `user_name` like '%SUN%' OR `user_name` like '%MOON%' 
and `login_datetime` BETWEEN '2013-03-01 00:00:00' and '2013-04-31 23:59:59') 
    NAND
(SELECT * FROM user WHERE `user_name` like '%RAJ%' OR `user_name` like '%MUTH%' 
and `login_datetime` BETWEEN '2013-04-01 00:00:00' and '2013-06-31 23:59:59') 
    NOR
 (SELECT * FROM user WHERE `user_name` like '%BAG%' OR `user_name` like '%LAP%'
 and `login_datetime` BETWEEN '2013-05-01 00:00:00' and '2013-07-31 23:59:59')

上面提到的查询是我的场景。在无法更改的情况下,我正在尝试为此编写一个查询。

笔记:

  1. 上述查询在单个表中执行。
  2. OR、NAND、NOR、AND运算可以根据情况互换。
  3. 这取决于用户,他需要如何搜索。

我尝试了很多方法来实现逻辑,但我在各个阶段都面临问题。

检查我的尝试: MySQL IN BETWEEN with no condition Doctrine Query from Mysql Select Query with OR and NAND

4

1 回答 1

1

NAND和NOR运算可以在SQL中进行如下操作:link

只需根据需要编辑以下查询。

SELECT * FROM user WHERE 
(`user_name` like '%TOM%' OR `user_name` like '%AN%' and `login_datetime` BETWEEN '2013-01-01 00:00:00' and '2013-02-31 23:59:59') OR
NOT ( --NOR
   (`user_name` like '%PHP%' OR `user_name` like '%BA%' and `login_datetime` BETWEEN '2013-02-01 00:00:00' and '2013-03-31 23:59:59') OR
   (`user_name` like '%SUN%' OR `user_name` like '%MOON%' and `login_datetime` BETWEEN '2013-03-01 00:00:00' and '2013-04-31 23:59:59')
) OR
NOT ( --NAND
   (`user_name` like '%RAJ%' OR `user_name` like '%MUTH%' and `login_datetime` BETWEEN '2013-04-01 00:00:00' and '2013-06-31 23:59:59') AND
   (`user_name` like '%BAG%' OR `user_name` like '%LAP%' and `login_datetime` BETWEEN '2013-05-01 00:00:00' and '2013-07-31 23:59:59')
)

在上面的示例中,如果第一个括号之间的条件为真或(第二个条件或第三个条件)或(第四个条件与非第五个条件),则返回所有记录。

注意条件是指括号之间的子句。

于 2013-06-11T12:39:25.397 回答