选择语句,但表是子查询?

时间:2018-09-01 21:30:06

标签: sql database subquery

我按角色划分用户,因此基本的 users 表中的信息很少,其余的存储在特定角色的单独表中。

所以我想在SQL中执行SELECT语句,但是Im选择的表必须是子查询的值。

SELECT * FROM (subquery);

在这种情况下,子查询是users表中users角色的值,因此我知道从哪里查找其余信息。

SELECT role FROM users WHERE email = 'jhondoe@example.com';

一起:

SELECT * FROM (SELECT role FROM users WHERE email = 'jhondoe@example.com');

(从理论上讲),这将变为:

SELECT * FROM students;
SELECT * FROM parents;
SELECT * FROM teachers;

取决于电子邮件;

1 个答案:

答案 0 :(得分:0)

您可以将查询连接到一个变量中,然后使用EXEC函数执行它:

declare @query nvarchar(MAX);
SET @query = 'SELECT * FROM ' + (SELECT role FROM users WHERE email = 'jhondoe@example.com');
EXEC(@query)

或者,如果您所有的表都具有相同的结构,则可以将它们合并在一起,然后选择与正确角色匹配的记录:

SELECT * FROM

(SELECT *, 'students' as PersonRole FROM students
UNION ALL
SELECT *, 'parents' as PersonRole FROM parents
UNION ALL
SELECT *, 'teachers' as PersonRole FROM teachers)

as tMerged

WHERE PersonRole IN (SELECT role FROM users WHERE email = 'jhondoe@example.com')