1

这可能很简单,但我目前还没有看到。尝试组合左外连接和内连接,以便从给定的一组表中获取任何可用的信息,所有信息都与 customer_id 相关

示例在设计上可能并不完美(我是根据我的实际查询编写的),但足以说明我的问题,即使其中一些表中有行,它也是一个空结果集。

样品表:

轮廓:

id_profile   nm_profile 
-----------  ----------  
1234         User profile     

订单:

id_order id_customer order_date    order_type
-------  ----------  ---------     ----------     
10308    1234        2017-09-18    Online
10309    1234        2018-09-18    Online 

评论:

   id_review  id_profile   id_order   text    score   
   ---------  ----------   --------   -----   ------
   (no rows for this id_profile)

询问:

SELECT c.id_customer, MIN(o.order_date) order_date, r.text review_text
FROM Customer c
JOIN Profile p ON c.id_customer = p.id_profile 
LEFT OUTER JOIN Orders o ON o.id_customer = c.id_customer AND o.order_type = 'Online'
LEFT OUTER JOIN Reviews r ON r.id_reviewer = p.id_profile AND r.score = 5
WHERE c.id_customer = 1234
GROUP BY c.id_customer

假设这些列匹配并且我能够运行上述查询,我​​正在尝试实现以下目标:

id_customer    order_date   review_text
-----------    ----------   -----------
1234           2017-09-18   <NULL>

这是一个更大的查询的一部分;试图将其分解为最基本的表达方式,以了解我可能做错了什么。已尝试避免连接中的 WHERE 子句,还尝试了 LEFT OUTER JOIN (SELECT ....) ,但没有运气。

提前致谢!

4

2 回答 2

2

您应该Reviews在聚合完成后加入:

SELECT t.id_customer, t.order_date, r.text review_text
FROM ( 
  SELECT c.id_customer, MIN(o.order_date) order_date
  FROM Customer c
  INNER JOIN Profile p ON c.id_customer = p.id_profile 
  LEFT JOIN Orders o ON o.id_customer = c.id_customer AND o.order_type = 'Online'
  WHERE c.id_customer = 1234
  GROUP BY c.id_customer
) t
LEFT JOIN Reviews r ON r.id_reviewer = t.id_customer AND r.score = 5;

演示

于 2021-09-11T10:16:55.143 回答
0

如果您只想要最大订单日期的所有评论信息,那么您可以汇总orders表格并加入其余部分:

SELECT c.id_customer, o.min_order_date, r.text as review_text
FROM Customer c JOIN
     Profile p ON c.id_customer = p.id_profile LEFT JOIN
     (SELECT o.id_customer, MIN(o.order_date) as min_order_date
      FROM Orders o
      WHERE o.order_type = 'Online'
      GROUP BY o.id_customer
     ) o
     ON o.id_customer = c.id_customer LEFT JOIN 
     Reviews r
     ON r.id_reviewer = p.id_profile AND r.score = 5
WHERE c.id_customer = 1234;

如果id_customer有多个评论,这将返回多行。你的问题没有说明如何处理。

于 2021-09-11T12:21:48.567 回答