你的 Postgres 版本是什么?如果您使用 Postgres 9.0 及以下版本,您的代码构造将不会运行。例如,这是不允许的:
SELECT
p.id,
p.firstname, p.lastname, p.address, -- these auxiliary fields is helpful to program users
count(*)
FROM
people p
JOIN visits v ON p.id = v.person_id
GROUP BY p.id
必须在 9.0 及以下版本上执行此操作:
SELECT
p.id,
p.firstname, p.lastname, p.address, -- these auxiliary fields is helpful to program users
count(*)
FROM
people p
JOIN visits v ON p.id = v.person_id
GROUP BY p.id
,p.firstname, p.lastname, p.address; -- these ancillary fields aids the RDBMS on preventing
-- programmers from accidentally committing the same mistake as MySQL programmers.
如果您使用的是 Postgres 9.1,您当然可以在 GROUP BY 中只使用一个字段,即使您在 SELECT 子句中有很多字段,只要该 GROUPed 字段是主键。因此这将运行:
SELECT
p.id,
p.firstname, p.lastname, p.address, -- these auxiliary fields is helpful to program users
count(*)
FROM
people p
JOIN visits v ON p.id = v.person_id
GROUP BY p.id
-- note that there's no need to repeat the SELECTed fields on GROUP BY clause
Postgres 9.1 可以促进对主键的功能依赖,因此只允许在 GROUP BY 子句中包含主键
SQL 小提琴示例:http ://sqlfiddle.com/#!1/3b857/3