duanpao4172 2014-02-25 09:29
浏览 12

具有if条件的mysql

My Question is I need to get two conditions first one if a user is admin I need to display all transactions but if a users is not admin I need to display his own transaction only. hers is the code that I tried but does not work.

Tables I have

  1. Users(Id, username, password, category ...etc)

  2. Transaction (Id, name, description, username, …etc)

SELECT IF (  (select category from users where username = ‘ali’ )==’A’) THEN
    Select * from transaction
ELSE
    Select * from transaction where username = ‘ali’

I also tried with this one but still no solution

SELECT IF(
  SELECT category FROM users where username= 'ali' AND category ='A',
  SELECT * FROM Transaction ,
  SELECT * FROM Transaction where username= 'ali'
)

Thanks

  • 写回答

3条回答 默认 最新

  • 普通网友 2014-02-25 09:34
    关注

    try this

    $where_text = ""; // initially blank
    
    // here $user variable contains the current username
    
    if($user!='admin') // check $user is admin or not if not 
    {
       $where_text = " WHERE username='$user' ";  // update $where_text
    }
    
    $query = "SELECT * FROM `transaction` ".$where_text; // apply in the query
    

    Now you can user your query by $query variable

    评论

报告相同问题?