加入如果ID存在则返回其他列

时间:2012-02-10 02:24:50

标签: mysql sql

我有两个现有的表{PeopleListEmployeeList}。我的问题是如果列中存在记录,如何创建连接其他表的查询,但如果不存在,则返回另一列的另一个记录。为了更清楚,我将在下面提供一些信息(虚拟记录):

PeopleList Table

AutoInc_ID     EmployeeID     Name
============================================
1              EMP001         Mr. John Doe
2                             Mr. Johnsons
3                             Mrs. Jane Smith
4              EMP002         Mr. Juan Dela Cruz

EmployeeList Table

EmployeeID     AliasName     DepartmentID
============================================
EMP001         JDoe          DEP001
EMP002         JDCruz        DEP001
EMP003         Alien         DEP051

我想要的结果是:

Result Table

AutoInc_ID     WorkerName
============================================
1              JDoe
2              Mr. Johnsons
3              Mr. Jane Smith
4              JDCruz

1 个答案:

答案 0 :(得分:1)

SELECT
  PeopleList.AutoInc_ID,
  IFNULL(EmployeeList.AliasName,PeopleList.Name) as WorkerName
FROM
  PeopleList
  LEFT JOIN EmployeeList ON PeopleList.EmployeeID=EmployeeList.EmployeeID
;