你可以交叉加入查询结果吗?

时间:2018-06-01 21:51:01

标签: sql postgresql

我有两个想要交叉加入的查询。这样的事情可能吗?

SELECT concat_ws(' ',first_name, last_name) adopters, d.name
FROM adopters
WHERE NOT EXISTS (SELECT adopter_id FROM dog_adoptions where adopter_id = id)
CROSS JOIN (SELECT name 
  FROM dogs 
  WHERE NOT EXISTS (SELECT dog_id FROM dog_adoptions WHERE dog_id = id)) d

上下文是sql小提琴链接:http://sqlfiddle.com/#!17/ac120/4349

问题是:“尚未选择狗的采纳者采用并生成所有可能的采用者和可用狗的组合。”

1 个答案:

答案 0 :(得分:1)

是的,你只需要正确的语法。 CROSS JOIN - 与所有JOIN 运算符一样 - 是FROM子句中识别的二进制运算符。所以你需要把它放在那里:

SELECT concat_ws(' ', a.first_name, a.last_name) as adopter, d.name
FROM adopters a CROSS JOIN
     (SELECT d.name 
      FROM dogs d
      WHERE NOT EXISTS (SELECT 1 FROM dog_adoptions da WHERE da.dog_id = d.id)
     ) d
WHERE NOT EXISTS (SELECT 1 FROM dog_adoptions da where da.adopter_id = a.id);

您还可以删除FROM子句中的子查询:

SELECT concat_ws(' ', a.first_name, a.last_name) as adopter, d.name
FROM adopters a CROSS JOIN
     dogs d
WHERE NOT EXISTS (SELECT 1 FROM dog_adoptions da where da.adopter_id = a.id) AND
      NOT EXISTS (SELECT 1 FROM dog_adoptions da WHERE da.dog_id = d.id)