【问题标题】:Fetching a result twice with deferend name使用不同的名称两次获取结果
【发布时间】:2012-10-25 04:55:01
【问题描述】:


我有 1 个名为 opentask 的任务表:
列:id、title、description、expires、creator_id、creator_name、executer_id、executer_name、priority_id、status_id
1 个名为 user 的表: 包含列:user_id、用户名
我想要的是创建一个查询,其中将有来自 opentask 表的所有列,其中 executer_id 将等于 user 表的 user_id 并且 creator_id 将再次等于 user_id。这会造成混淆,因为第一个相等性排除了第二个相等性。

因此,我需要以某种方式创建一个查询,其中我将包含执行者的用户名,其中包含“opentask.executer_id=user_user_id”之类的内容,同时有时间我会再次为创建者添加用户名(作为不同的名称?),例如“where opentask.executer_id=user_user_id”

所以我试试这个,当然我知道这缺少一些东西,可以你帮忙?

SELECT DISTINCT id, title, description, expires, creator_id, executer_id, oc_opentask.priority_id, oc_opentask.status_id, priority_name, status_name, user_id, username, (SELECT username FROM oc_opentask, oc_user WHERE oc_opentask.creator_id=oc_user.user_id) AS username2 FROM oc_opentask, oc_opentask_priority, oc_user, oc_opentask_status WHERE oc_opentask.priority_id=oc_opentask_priority.priority_id AND oc_opentask.executer_id=oc_user.user_id AND oc_opentask.status_id=oc_opentask_status.status_id ORDER BY oc_opentask.expires DESC

【问题讨论】:

标签: mysql select double rename


【解决方案1】:

ReJOIN 表 oc_user 两次使用不同的别名 creators 和 executers 像这样:

SELECT DISTINCT 
  t.*, 
  creators.user_name 'Creator name',
  executers.username 'Executor name', 
  tp.priority_name, 
  s.status_name
FROM oc_opentask t 
INNER JOIN oc_opentask_priority tp        ON t.priority_id = tp.priority_id
INNER JOIN oc_user              executers ON t.executer_id = executes.user_id
INNER JOIN oc_user              creators  ON t.creator_id  = creators.user_id
INNER JOIN oc_opentask_status   s         ON t.status_id   = s.status_id
ORDER BY t.expires DESC

【讨论】:

  • 非常感谢您准确快速的回答。
猜你喜欢
  • 1970-01-01
  • 2013-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-15
  • 1970-01-01
  • 1970-01-01
  • 2019-02-12
相关资源
最近更新 更多