【发布时间】:2018-04-30 02:44:06
【问题描述】:
我有以下数据库表
User List
------ ------
userId (PK) listId (PK)
fullName description
addedById (FK with userId in User table)
modifiedById (FK with userId in User table)
我需要从 List table 中提取所有数据,但我不需要显示 addedById 和 modifiedById 的 ID,而是需要从 User 表中拉出 fullName。
此查询有效,并为我提供了所需的数据。但是,我不确定是否有更好的方法来构建这个查询?我不希望在我的主选择查询中有多个子选择查询,主要是因为性能问题。
select t1.[description],
t1.addedById,
t1.modifiedById,
(select fullName from dbo.User where userId = t1.addedById) as [AddedByUser],
(select fullName from dbo.User where userId = t1.modifiedById) as [ModifiedByUser]
from dbo.List t1
如果有人能对查询提出改进建议或建议保持原样,我将不胜感激。
谢谢。
【问题讨论】:
-
改为使用 LEFT JOIN。
-
您的查询没问题,假设
userId上有索引。另一种方法是LEFT JOIN。两种方法的性能应该非常相似。 -
SO 题外话。我建议在 CodeReview 上发帖。
-
为什么这个问题会被否决?
标签: sql sql-server select subquery