简体   繁体   English

MySQL 2外键到相同的主键

[英]MySQL 2 foreign keys to the same primary key

So I have 2 tables; 所以我有2张桌子; a task table and an employee table. 任务表和员工表。

A task is created by an employee and maintains the id of the employee that creates it as creator_id. 任务是由员工创建的,并且将创建该任务的员工的ID保留为creator_id。

A task is assigned to an employee and maintains the id of the employee it is assigned to as responsible_id. 任务已分配给员工,并且将其分配给该员工的ID保留为负责人ID。

The creator of the task and the employee it is assigned to can be different people. 任务的创建者和分配给它的员工可以是不同的人。

How do I write a select statement that allows me to display the full names of both the employee that created the task and the employee that is assigned to it. 如何编写一个选择语句,使我可以显示创建任务的员工和分配给该员工的员工的全名。

I think it might look something like this: 我认为它可能看起来像这样:

SELECT Task.Description, Employee1.name, Employee2.name
FROM Task, Employee Employee1, Employee Employee2
WHERE Task.creator_id = Employee1.id
AND Task.responsible_id = Employee2.id;

I have tried variations of this but it either returns errors or hits the memory limit. 我尝试了这种方式的变体,但是它要么返回错误,要么达到内存限制。

Where am I going wrong? 我要去哪里错了?

From your description the query is correct but you should consider rewriting it to use explicit ANSI joins: 根据您的描述,查询是正确的,但是您应该考虑使用明确的ANSI连接重写它:

SELECT Task.Description, Employee1.name, Employee2.name
FROM Task
JOIN Employee Employee1 ON Task.creator_id = Employee1.id
JOIN Employee Employee2 ON Task.responsible_id = Employee2.id;

Sample SQL Fiddle 示例SQL提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM