如何查询由中间表连接的三个表?

时间:2012-04-29 14:07:54

标签: sql sql-server-2008

我只有一个可能非常愚蠢的问题,但我无法解决这个问题。

我目前有3张桌子:

PROJECT    
PROJECT_CATEGORY     
CATEGORY

现在PROJECT_CATEGORY是一个中间表,因此它只包含来自PROJECTCATEGORY的主键,例如pIDcID

如果表pID中有CATEGORY,我知道如何编写查询但在这种情况下我只有中间表。那么我如何创建一个查询这三个表的查询然后它会显示所有类别以及它们分配给哪些项目?

2 个答案:

答案 0 :(得分:7)

select c.*, p.* 
from categories c
inner join PROJECT_CATEGORY pc on pc.category_id = c.id
inner join projects p on pc.project_id = p.id

答案 1 :(得分:2)

如果我理解正确,您想要查找某个类别是否包含项目。以下查询显示了与给定类别关联的项目数。

如果您想要与所有类别关联的所有项目的列表,则可以使用第二个查询。由于没有与此类别关联的项目,类别4 将不会显示在第二个结果中,因为INNER JOIN。如果您希望显示类别4,则必须将INNER JOIN更改为LEFT OUTER JOIN

Click here to view the demo in SQL Fiddle.

脚本

CREATE TABLE project 
(
  projectid INT NOT NULL 
  , projectname VARCHAR(20) NOT NULL
);

CREATE TABLE projectcategory
(
    projectid   INT NOT NULL 
  , categoryid  INT NOT NULL
);

CREATE TABLE category
(
    categoryid      INT NOT NULL
  , categoryname    VARCHAR(20) NOT NULL
);

INSERT INTO project (projectid, projectname) VALUES 
    (1, 'project 1'),
    (2, 'project 2'),
    (3, 'project 3');

INSERT INTO category (categoryid, categoryname) VALUES 
    (1, 'category 1'),
    (2, 'category 2'),
    (3, 'category 3'),
    (4, 'category 4');

INSERT INTO projectcategory (projectid, categoryid) VALUES 
    (1, 1),
    (3, 2),
    (2, 1),
    (2, 2),
    (2, 3),
    (2, 2);

SELECT          c.categoryid
            ,   c.categoryname
            ,   COUNT(pc.categoryid) Number_Of_Projects
FROM            category c 
left outer join projectcategory pc 
on              pc.categoryid = c.categoryid
GROUP BY        c.categoryid
ORDER BY        c.categoryname;

SELECT          c.categoryid
            ,   c.categoryname
            ,   p.projectid
            ,   p.projectname
FROM            category c 
inner join      projectcategory pc 
on              pc.categoryid = c.categoryid
inner join      project p
on              p.projectid = pc.projectid
ORDER BY        c.categoryname;

输出

CATEGORYID CATEGORYNAME NUMBER_OF_PROJECTS
---------- ------------ ------------------
1          category 1           2
2          category 2           3
3          category 3           1
4          category 4           0

CATEGORYID CATEGORYNAME PROJECTID PROJECTNAME
---------- ------------ --------- -----------
1          category 1       1      project 1
1          category 1       2      project 2
2          category 2       3      project 3
2          category 2       2      project 2
2          category 2       2      project 2
3          category 3       2      project 2