如何在 SQL 中将表连接到子查询结果?

Posted

技术标签:

【中文标题】如何在 SQL 中将表连接到子查询结果?【英文标题】:How to join tables to subquery results in SQL? 【发布时间】:2021-01-31 16:07:45 【问题描述】:

我有以下查询:

SELECT customer_id, product_id, COUNT(product_id) CUSTOMER_PRODUCT_COUNT
  2  FROM Order_Details
  3  Group BY customer_id, product_id
  4  HAVING COUNT(product_id) > 1;

结果如下表:

CUSTOMER_ID PRODUCT_ID CUSTOMER_PRODUCT_COUNT
---------- ---------- ----------------------
C1         P3                              2

我正在尝试将其用作子查询,以将 customer_ID 从 Customer 表连接到 customer_name。 product_id 列也存在于另一个名为 Order_Details 的表中,我也在尝试加入该表,以便提供客户的地址:

到目前为止,我提出了以下查询,它给出了一个错误:

SELECT c.customer_name, a.country, a.zone, a.district, a.city
  2  FROM (
  3     SELECT customer_id, product_id, COUNT(product_id) CUSTOMER_PRODUCT_COUNT
  4     FROM Order_Details
  5     Group BY customer_id, product_id
  6     HAVING COUNT(product_id) > 1) AS o
  7  JOIN Customer c ON c.customer_id = o.customer_id
  8  JOIN Address a ON a.address_id = o.address_id;

【问题讨论】:

您使用的是什么版本的 SQL Server? 你遇到了什么错误? ORA-00933: SQL 命令未正确结束,是错误,它突出显示为启动错误的 AS o 【参考方案1】:

这个查询看起来正确:

SELECT c.customer_name, a.country, a.zone, a.district, a.city
FROM (SELECT customer_id, product_id, COUNT(product_id) CUSTOMER_PRODUCT_COUNT
      FROM Order_Details
      GROUP BY customer_id, product_id
      HAVING COUNT(product_id) > 1
     ) AS o JOIN
     Customer c
     ON c.customer_id = o.customer_id JOIN
     Address a
     ON a.address_id = o.address_id;

除了对o.address_id 的引用(我猜想是c.address_id)之外,我只能想到两个可能的问题:

列引用不正确。 您使用的是 Oracle,它不允许在 FROM 子句中使用 as

无论如何,我都会这样写查询:

SELECT c.customer_name, a.country, a.zone, a.district, a.city
FROM (SELECT customer_id, product_id, COUNT(*) as CUSTOMER_PRODUCT_COUNT
      FROM Order_Details od
      GROUP BY customer_id, product_id
      HAVING COUNT(*) > 1
     ) o JOIN
     Customer c
     ON c.customer_id = o.customer_id JOIN
     Address a
     ON a.address_id = c.address_id;

没有必要计算非NULLvalues in a column when you simply want to count rows. That is whatCOUNT(*)`。

【讨论】:

我确实在使用 Oracle,但它仍然给出错误:第 10 行的错误:ORA-00904: "O"."ADDRESS_ID": invalid identifier @SamitPaudel 。 . .我想你打算c.address_id 是第 10 行的错误:ORA-00904:“C”。“ADDRESS_ID”:标识符无效

以上是关于如何在 SQL 中将表连接到子查询结果?的主要内容,如果未能解决你的问题,请参考以下文章

如何将表连接到联合查询的结果

Hibernate:如何在注释中将三个 3 表连接到一个连接表中?

如何根据之前的记录将 SQL 表连接到自身?

我不知道如何在Laravel中将表连接到另一个表

如何将学生和评估表连接到一个视图中?

如何在熊猫中将sql查询结果保存到csv