gpt4 book ai didi

SQL,获取外键值。外键引用同一张表

转载 作者:行者123 更新时间:2023-12-01 23:02:50 28 4
gpt4 key购买 nike

MS SQL Server 数据库。

我有这个简单的结构:(抱歉主键不在正确的位置)

在 TEACHER 表中,我有一个外键“Chief”,它引用了 TEACHER.ID(同一个表)。在执行 SELECT 查询时,如何获得不是整数(Teacher.ID),而是酋长姓名(TEACHER.Name for Chief)?

这个只有一个整数(酋长的ID):

SELECT DEPARTMENT.Name, TEACHER.Name, TEACHER.IDCode, POST.Name, TEACHER.Tel, TEACHER.Salary, TEACHER.Rise, TEACHER.HireDate, Chief
FROM TEACHER, DEPARTMENT, POST
WHERE TEACHER.ID_Post = POST.ID AND
TEACHER.ID_Department = DEPARTMENT.ID;
GO

最佳答案

JOIN TEACHER 表再次,像这样:

SELECT 
d.Name,
t.Name,
t.IDCode,
p.Name,
t.Tel,
t.Salary,
t.Rise,
t.HireDate,
chief.Name 'Chief Name'
FROM TEACHER t
INNER JOIN TEACHER chief ON t.Chief = chief.ID
INNER JOIN DEPARTMENT d ON t.ID_Department = d.ID
INNER JOIN POST p ON t.ID_Post = p.ID;

并使用 ANS-SQL-92 JOIN 语法而不是您在查询中使用的旧语法。 They are the same ,但这是推荐的语法。

关于SQL,获取外键值。外键引用同一张表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13438753/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com