2

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

我目前有3张桌子:

PROJECT    
PROJECT_CATEGORY     
CATEGORY

NowPROJECT_CATEGORY是一个中间表,因此它只包含来自PROJECTandCATEGORY的主键pIDcID.

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

4

2 回答 2

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
于 2012-04-29T14:10:43.860 回答
2

如果我理解正确,您想查找一个类别是否有项目。以下查询显示有多少项目与给定类别相关联。

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

单击此处查看 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
于 2012-04-29T14:19:51.110 回答