我有4个表,员工,技能,兴趣和目标。我正在尝试显示一个员工的所有技能、兴趣和目标,但每个技能、兴趣和目标表中的值数量不同。例如,员工1有3个兴趣、5个技能和4个目标。我想要做的是显示5行和5列。第1列的employee 1的名字将列出5次。第2列将具有员工的技能。第3列的员工的权益为2个空值。第4列将员工的目标设置为一个空。如下所示

我尝试了许多不同的连接,但我总是得到所有可能的组合作为输出。
在这方面的任何帮助都将非常感谢。
发布于 2019-07-13 04:15:29
好吧,这是一个丑陋的解决方案,但它对我来说很有效,至少在SQL Server中是这样:
WITH employees_temp as (
SELECT employees.first_name, row_number() over (ORDER BY id) as RowNum
FROM employees
WHERE employees.first_name LIKE 'will'
),
skills_temp as (
SELECT skills.skill, , row_number() over (ORDER BY skills.employee_id) as RowNum
FROM skills
INNER JOIN employees
ON skills.employee_id = employees.id
WHERE employees.first_name LIKE 'will'
),
goals_temp as (
SELECT goals.goal, , row_number() over (ORDER BY goals.employee_id) as RowNum
FROM goals
INNER JOIN employees
ON goals.employee_id = employees.id
WHERE employees.first_name LIKE 'will'
),
interests_temp as (
SELECT interests.interest, , row_number() over (ORDER BY interests.employee_id) as RowNum
FROM interests
INNER JOIN employees
ON interests.employee_id = employees.id
WHERE employees.first_name LIKE 'will'
)
select employees_temp.first_name, skills_temp.skill, goals_temp.goal, interests_temp.interest
from employees_temp
full outer join skills_temp
on employees_temp.RowNum = skills_temp.RowNum
full outer join goals_temp
on employees_temp.RowNum = goals_temp.RowNum
full outer join interests_temp
on employees_temp.RowNum = interests_temp.RowNum这样做的目的是为四个查询中的每一个选择所需的数据,并添加一个行号。然后,我们将所有这四个连接在一起,在行号上连接。我们需要一个行号来连接,否则,如您所见,它将创建所有可能的组合。行号起到了一种虚拟ID的作用,我们可以加入以防止这种情况发生。
以下是一些注意事项:
https://stackoverflow.com/questions/57011790
复制相似问题