有条件地加入一张桌子

时间:2013-05-20 15:33:14

标签: sql postgresql

我的测试表是:

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;

有什么其他方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

select *
from
    products p
    left join
    reviews r on r.product = p.product and p.show_reviews
;