通过WHERE访问结果

时间:2012-11-06 16:05:55

标签: sql select where

在我的第一个问题here之后,我得到了以下正确且经过测试的代码:

SELECT DISTINCT
id, title, description, expires,
creator_id,executer_id,
oc_opentask.priority_id,
oc_opentask.status_id, priority_name, status_name,
oc_user1.username AS executer_username,
oc_user2.username AS creator_username
FROM oc_opentask
INNER JOIN oc_opentask_priority 
ON oc_opentask.priority_id=oc_opentask_priority.priority_id
INNER JOIN oc_opentask_status 
ON oc_opentask.status_id=oc_opentask_status.status_id
INNER JOIN oc_user AS oc_user1 
ON oc_opentask.executer_id=oc_user1.user_id
INNER JOIN oc_user AS oc_user2 
ON oc_opentask.creator_id=oc_user2.user_id

我的下一个问题是:我想要使用WHERE属性访问那些executer_usernamecreator_username以将其与值进行比较,因此我正在尝试的是弹出mystake的是:

SELECT DISTINCT
id, title, description, expires,
creator_id,executer_id,
oc_opentask.priority_id,
oc_opentask.status_id, priority_name, status_name,
oc_user1.username AS executer_username,
oc_user2.username AS creator_username
FROM oc_opentask
INNER JOIN oc_opentask_priority 
ON oc_opentask.priority_id=oc_opentask_priority.priority_id
INNER JOIN oc_opentask_status 
ON oc_opentask.status_id=oc_opentask_status.status_id
INNER JOIN oc_user AS oc_user1 
ON oc_opentask.executer_id=oc_user1.user_id
INNER JOIN oc_user AS oc_user2 
ON oc_opentask.creator_id=oc_user2.user_id
WHERE oc_opentask.creator_username='bill' 

bill确实存在于db中,但我访问该值的命令不正确,any1可以帮助我吗?感谢

3 个答案:

答案 0 :(得分:1)

您有一个列别名:

oc_user2.username AS creator_username

并在你的where子句中使用别名。您需要使用实际的列名称,因此请将其更改为:

where oc_user2.username = 'bill'

答案 1 :(得分:0)

您使用了错误的表来获取where子句中的创建者名称。使用oc_user2表获取用户名(创建者名称)。另外我还在考虑可能存在case相关问题,因此建议在比较之前使用LOWER函数,如下所示:

    SELECT DISTINCT
       id, title, description, expires,
       creator_id,executer_id,
       oc_opentask.priority_id,
       oc_opentask.status_id, priority_name, status_name,
       oc_user1.username AS executer_username,
       oc_user2.username AS creator_username
    FROM oc_opentask
    INNER JOIN oc_opentask_priority 
       ON oc_opentask.priority_id=oc_opentask_priority.priority_id
    INNER JOIN oc_opentask_status 
       ON oc_opentask.status_id=oc_opentask_status.status_id
    INNER JOIN oc_user AS oc_user1 
       ON oc_opentask.executer_id=oc_user1.user_id
    INNER JOIN oc_user AS oc_user2 
       ON oc_opentask.creator_id=oc_user2.user_id
    WHERE LOWER(oc_user2.username)=LOWER('bill')

我只是在右侧使用LOWER,使其与any valid name的案例无关,无论情况如何。

答案 2 :(得分:0)

如果这是MySQL,只需使用HAVING代替WHERE。然后,无论您是指定原始列名还是已定义的别名,都将永远不会出现问题。 HAVING还允许你使用聚合函数的结果,即HAVING MAX(薪水)> 40,而WHERE也失败了。