具有IF条件MySQL的SELECT语句

时间:2014-12-18 03:37:23

标签: php mysql

我有一张桌子,它有列

menu_id , parent_id, controller , action , action_edit , action_view , 


select * from test where  
( action like 'my_action.php' or 
action_edit like '%my_action.php%' or 
action_view like '%my_action.php%'
) AND parent_id !=0 ORDER BY `controller` ASC 

actionaction_viewaction_edithome.php时 - >我想省略parent_id !=0

我尝试使用

AND IF(action='home.php' OR action_view='home.php' OR action_edit='home.php',parent !=0,)代替AND parent_id !=0,但它给我一个令牌不匹配错误

但没有工作,提前谢谢你:)

5 个答案:

答案 0 :(得分:1)

尝试这样的事情:

select *
from test
where  'home.php' not in (action, action_view, action_edit) or parent_id <> 0) and
       (action like 'my_action.php' or action_edit like '%my_action.php%' or 
        action_view like '%my_action.php%'
       )

编辑:

not innot in很危险。让我们使用coalesce()来阻止问题:

select *
from test
where  'home.php' not in (coalesce(action, ''), coalesce(action_view, ''), coalesce(action_edit, '')) or parent_id <> 0) and
       (action like 'my_action.php' or action_edit like '%my_action.php%' or 
        action_view like '%my_action.php%'
       )

答案 1 :(得分:0)

也许你想要这个?

select * from test where  
(( action like 'my_action.php' or 
   action_edit like '%my_action.php%' or 
   action_view like '%my_action.php%'
 ) AND parent_id !=0)
OR 
( action='home.php' OR 
  action_view='home.php' OR 
  action_edit='home.php') 
ORDER BY `controller` ASC

答案 2 :(得分:0)

试试这个:

SELECT * FROM test
  WHERE NOT EXISTS ((SELECT A.* FROM test A)
                   JOIN (SELECT B.* FROM test B WHERE 
                         B.action like 'my_action.php'
                         OR B.action_edit like '%my_action.php%'
                         OR B.action_view like '%my_action.php%')
                   ON A.parent_id !=0)
ORDER BY `controller` ASC

答案 3 :(得分:0)

嗨最后我有一个解决方案

select * from test where  
( action like 'my_action.php' or 
action_edit like '%my_action.php%' or 
action_view like '%my_action.php%'
) AND parent_id !=0 ORDER BY `controller` ASC 

而不是我使用的parent_id !=0

IF(action='home.php' OR action_view='home.php' OR action_edit='home.php',parent=0,parent!=0)

现在它的工作,谢谢你的帮助人:)。我发布了我的答案,因为我认为这将对未来有类似问题的用户提供帮助:)

答案 4 :(得分:-1)

怎么样:

select * from test where  
(( action like 'my_action.php' or 
action_edit like '%my_action.php%' or 
action_view like '%my_action.php%'
)) AND (parent_id !=0)) 
ORDER BY `controller` ASC