我正在尝试为mysql (Search Module)
编写一个查询,因为要在同一个表中执行select操作,我遇到了困难。
我的查询:
(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')
上面提到的查询是我的场景..如果无法更改,我正在尝试为此编写查询。
我尝试了许多方法来实现逻辑,但我在所有阶段都面临着问题。
检查我的尝试: MySQL IN BETWEEN with no condition Doctrine Query from Mysql Select Query with OR and NAND
答案 0 :(得分: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')
)
在上面的例子中,返回所有记录,其中第一个括号之间的条件为真OR(第二个条件NOR第三个条件)或(第四个条件NAND第五个条件)。
注意:条件是指括号内的条款。