如果我理解正确,您想查找一个类别是否有项目。以下查询显示有多少项目与给定类别相关联。
如果您想要与所有类别关联的所有项目的列表,您可以使用第二个查询。类别 4将不会显示在第二个结果中INNER JOIN
,因为没有与该类别关联的项目。如果要显示类别 4,则必须更改INNER JOIN
为LEFT 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