SQL 多对多查询
表Person: personID, personName
表TaskPerson: taskID,personID
每个任务有多个人担当,每个人同时也担当多人任务。
求教SQL文,查询1:每个任务对应的担当者
查询2:每个人承担的任务
谢谢! 展开
1、创建测试表,
create table test_task(taskID varchar2(20),taskName varchar2(200));
create table test_person(personID varchar2(20),personName varchar2(200));
create table test_task_person(taskID varchar2(20),personID varchar2(200));
2、插入测试数据;
insert into test_task values (101,'Task_101');
insert into test_task values (102,'Task_102');
insert into test_task values (103,'Task_103');
insert into test_person values (1001,'Person_1001');
insert into test_person values (1002,'Person_1002');
insert into test_person values (1003,'Person_1003');
insert into test_task_person values (101,1001);
insert into test_task_person values (101,1002);
insert into test_task_person values (102,1001);
insert into test_task_person values (102,1003);
insert into test_task_person values (103,1001);
insert into test_task_person values (103,1003);
commit;
3、查询1,查询每个任务对应的担当者;select t.*, b.personName from test_task_person t, test_person b where t.personID = b.personID;
4、查询2,查询每个人承担的任务;select t.*, b.taskName from test_task_person t, test_task b where t.taskID = b.taskID;
查询1:每个任务对应的担当者
SELECT t.taskID, t.taskName, tp.personID, p.personName
FROM task t
LEFT JOIN TaskPerson tp ON t.taskID = tp.taskID
LEFT JOIN Person p ON p.personID = tp.personID
查询2:每个人承担的任务
SELECT p.personID, p.personName, tp.taskID, t.taskName
FROM Person p
LEFT JOIN TaskPerson tp ON p.personID = tp.personID
LEFT JOIN Task t ON t.taskID = tp.taskID
select taskName, personName from Task a,Person b,TaskPerson c
where a.taskID=c.taskID and b.personID=c.personID
group by taskName, personName
查询2:每个人承担的任务
select personName,taskName from Task a,Person b,TaskPerson c
where a.taskID=c.taskID and b.personID=c.personID
group by taskName, personName
两个结果好象是一样的
SQL1: select a.taskName, c.personName from task a, TaskPerson b, Person c
where a. taskID = b.taskID and b.personID = c.personID
SQL2: select a.taskName, c.personName from task a, TaskPerson b, Person c
where a. taskID = b.taskID and b.personID = c.personID gourpby c.personName
select taskID,taskName,personName from
TaskPerson,Person,Task
where TaskPerson.personID=Person.personID and
Task.taskID=TaskPerson.taskID
第二个:
select personName,taskID,taskName from
TaskPerson,Person,task
where TaskPerson.personID=Person.personID and
Task.taskID=TaskPerson.taskID