MySQL LEFT 加入别名问题

MySQL LEFT join alias issue

(已编辑)我正在尝试编写一个 sql 连接。

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'

现在我想按性别和级别搜索数据。但是,它没有出现

你在 where 条件中使用了别名,你不能这样做,如果你想使用列别名,你必须使用完整的列名或使用 having 子句

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

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

同样适用于

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

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

如果要将它与列名一起使用,则需要使用反引号。此外,您不能在 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'