我有几张桌子的DB,其中2个被定义为:
CREATE TABLE [projects] (
[id] INTEGER NOT NULL PRIMARY KEY,
[code] VARCHAR(128) UNIQUE NOT NULL COLLATE NOCASE,
[name] VARCHAR(128) DEFAULT "Not Set" NOT NULL COLLATE NOCASE
)
CREATE TABLE [tasks] (
[id] INTEGER NOT NULL PRIMARY KEY,
[project_id] INTEGER NOT NULL,
[notes] VARCHAR(512) DEFAULT 'Not Set' NOT NULL COLLATE NOCASE,
[start] DATE NOT NULL,
[finish] DATE NOT NULL,
[rate_id] INTEGER DEFAULT 1 NOT NULL
)
我有这个查询返回项目详细信息列表,其中包含使用次数:
SELECT p.*, count(t.project_id) as length
FROM projects as p, tasks as t
WHERE p.id=t.project_id
GROUP BY p.code
ORDER BY length DESC;
但是我发现如果没有使用项目ID,它将返回比项目小的列表(没有给定项目ID的任务)。
有没有办法以与我当前查询相同的格式创建项目的完整列表并添加长度,但包括所有项目,对于那些没有任务长度的项目将有0?
答案 0 :(得分:1)
要获得没有任务的项目,请使用left outer join。
ifnull函数会将NULL
转换为零:
SELECT p.*, IFNULL(COUNT(t.project_id), 0) AS length
FROM projects AS p
LEFT JOIN tasks AS t ON p.id = t.project_id
GROUP BY p.code
ORDER BY length DESC