我有以下数据库模式:
CREATE SCHEMA products;
CREATE TABLE products.product_group (
id bigserial NOT NULL PRIMARY KEY,
name varchar(255) NOT NULL
)
CREATE TABLE products.product (
id bigserial NOT NULL PRIMARY KEY,
name varchar(255) NOT NULL,
product_group_id bigint REFERENCES products.product_group(id),
color varchar(255) NOT NULL
)
INSERT INTO products.product_group(name) values ('product group 1');
INSERT INTO products.product(name,product_group_id,color) VALUES ('product 1',1,'RED');
INSERT INTO products.product(name,product_group_id,color) VALUES ('product 1',1,'BLUE');
INSERT INTO products.product(name,product_group_id,color) VALUES ('product 1',1,'GREEN');
如果我执行以下查询:
SELECT count(*), pg.name FROM products.product p
LEFT JOIN products.product_group pg ON (p.product_group_id=pg.id)
WHERE pg.id = 1
AND p.color = 'RED'
GROUP BY pg.name
我得到了结果:
1;"product group 1"
如果我执行以下查询:
SELECT count(*), pg.name FROM products.product p
LEFT JOIN products.product_group pg ON (p.product_group_id=pg.id)
WHERE pg.id = 1
AND p.color = 'YELLOW'
GROUP BY pg.name
我得没有结果,我想要:
0;"product group 1"
我如何更改查询以获得我想要的结果?
答案 0 :(得分:3)
SELECT count(p.name), pg.name
FROM
products.product p
right JOIN
products.product_group pg ON
p.product_group_id=pg.id
and pg.id = 1
and p.color = 'YELLOW'
GROUP BY pg.name;
count | name
-------+-----------------
0 | product group 1
您的原始查询有两个问题。首先,外部连接是向后的。其次,where条件将外连接转换为内连接,因此必须将where
条件移至join
条件。
计数还有另一个问题。您必须在count
中声明一个列,以便它只计算该列不为空的位置。