SQL Query简单的问题

时间:2011-09-26 22:56:09

标签: php mysql

只是想知道我是否遗漏了一些东西:

$sql = "SELECT DISTINCT usr.id, 
CONCAT(usr.username, '".PHP_EOL."' ) as username 
FROM #__ads AS a 
RIGHT JOIN #__users 
WHERE gid= '19' AS usr  
    ON usr.id = a.userid 
ORDER BY usr.username";

当我删除WHERE gid ='19'部分时,它是否有效,是否在错误的位置? gid列仅存在于__users表中。

谢谢!

编辑:得到它,只需将Where子句放在ORDER BY之前。

2 个答案:

答案 0 :(得分:1)

where子句必须在任何连接之后出现:

$sql = "SELECT DISTINCT usr.id
             , CONCAT(usr.username, '".PHP_EOL."' ) as username
        FROM #__ads AS a
        RIGHT JOIN #__users AS usr
        ON usr.id = a.userid 
        WHERE gid= '19'
        ORDER BY usr.username";

答案 1 :(得分:0)

假设您只想要来自#__users usr.gid= '19'

的行
SELECT DISTINCT usr.id, 
                CONCAT(usr.username, '".PHP_EOL."' ) as username 
FROM #__ads AS a 
RIGHT JOIN #__users as usr  ON usr.id = a.userid  
WHERE usr.gid= '19' 
ORDER BY usr.username

替代

SELECT DISTINCT usr.id, 
                CONCAT(usr.username, '".PHP_EOL."' ) as username 
FROM #__ads AS a 
RIGHT JOIN #__users as usr  ON usr.id = a.userid  
                            AND usr.gid= '19' 
ORDER BY usr.username

会为您提供#__users的所有行,但只会加入匹配usr.gid= '19'

的行