2015-03-31 128 views
1

(編輯)我想寫一個sql連接。MySQL左連接別名問題

SELECT a.id, 
        a.name, 
        c.name AS 'gender', 
        a.email, 
        a.phone, 
        a.address, 
        b.name AS 'level', 
        a.level_id 
      FROM ms_user a 
      LEFT JOIN lt_user_level b 
      ON a.level_id = b.id 
      LEFT JOIN lt_user_gender c 
      ON a.gender_id = c.id 
      WHERE a.id LIKE '%".$id."%' 
      AND a.name LIKE '%".$name."%' 
      AND 'gender' LIKE '%".$gender."%' 
      AND a.email LIKE '%".$email."%'     
      AND a.phone LIKE '%".$phone."%'         
      AND a.address LIKE '%".$address."%' 
      AND 'level' LIKE '%".$level."%'             
      AND a.status <> 'D' 

現在我想按性別和級別搜索數據。但是,它不會出現

回答

0

如果要將其與列名一起使用,則需要使用反引號。你也不能使用where子句中的別名(由Barmar。正確地指出)

試試這個

SELECT a.id, 
       a.name, 
       c.name AS `gender`, 
       a.email, 
       a.phone, 
       a.address, 
       b.name AS `level`, 
       a.level_id 
     FROM ms_user a 
     LEFT JOIN lt_user_level b 
     ON a.level_id = b.id 
     LEFT JOIN lt_user_gender c 
     ON a.gender_id = c.id 
     WHERE a.id LIKE '%".$id."%' 
     AND a.name LIKE '%".$name."%' 
     AND c.name LIKE '%".$gender."%' 
     AND a.email LIKE '%".$email."%'     
     AND a.phone LIKE '%".$phone."%'         
     AND a.address LIKE '%".$address."%' 
     AND b.name LIKE '%".$level."%'             
     AND a.status <> 'D' 
+0

不能引用別名在'WHERE'條款。 – Barmar 2015-03-31 07:38:42

+0

@Barmar: - 謝謝你指出。更新了我的答案! – 2015-03-31 07:40:09

+0

感謝您的回覆,謝謝 – littlecorn 2015-03-31 08:02:00

1

你在WHERE條件使用別名,你不能這樣做,你必須使用完整的列名,或者如果你想使用列別名

AND 'gender' LIKE '%".$gender."%' 
使用having子句

AND c.name LIKE '%".$gender."%' 

類似地,對於

AND 'level' LIKE '%".$level."%' 

AND b.name LIKE '%".$level."%'