1

我的测试表是:

create table products (
  product varchar(50) primary key,
  show_reviews boolean
);
create table reviews (
  review_id integer primary key,
  product varchar(50) references products (product),
  review varchar(200)
);
insert into products (product, show_reviews) values
  ('blender', true),
  ('toaster', false),
  ('microwave', true);
insert into reviews (review_id, product, review) values
  (1, 'blender', 'Excellent'),
  (2, 'toaster', 'Terrible'),
  (3, 'toaster', 'Would not buy again'),
  (4, 'microwave', 'Wonderful'),
  (5, 'microwave', 'Splendid');

我正在寻找一个产生这样的结果集的查询:

  product    |  show_reviews  |  review_id  |  review
-------------+----------------+-------------+----------
  blender    |  true          |  1          |  Excellent
  toaster    |  false         |  null       |  null
  microwave  |  true          |  4          |  Wonderful
  microwave  |  true          |  5          |  Splendid

本质上,我想reviews根据show_reviews. 这是我想出的:

select products.*, rev.*
from products
left join (
    select reviews.*
    from reviews
    join products as p on p.product = reviews.product
    where p.show_reviews = true
  ) as rev on rev.product = products.product;

还有哪些其他方法可以做到这一点?

4

1 回答 1

1
select *
from
    products p
    left join
    reviews r on r.product = p.product and p.show_reviews
;
于 2013-05-20T15:50:59.607 回答