简体   繁体   English

SQL 内连接 2 个表

[英]SQL Inner Join 2 Tables

Hoping to get some help with this, I have made a few attempts at an inner join that shows all 'Product' information from the product table for, any product that has sold more than 10 units using an inner join.希望得到一些帮助,我尝试了一些内部连接,显示产品表中的所有“产品”信息,任何使用内部连接销售超过 10 件的产品。

PRODUCT TABLE (Columns)
P_CODE, P_DESCRIPT, P_INDATE, P_QOH, P_MIN, P_PRICE, P_DISCOUNT, V_CODE

LINE TABLE (Columns) this table shows the lines/information for each 
invoice

INV_NUMBER, LINE NUMBER, P_CODE, LINE_UNITS, LINE_PRICE, LINE_TOTAL

I understand that I have to make the join using the common key attribute (p_code) but I cannot figure out how to do the sum within the inner join.我知道我必须使用公共键属性 (p_code) 进行连接,但我无法弄清楚如何在内部连接中进行求和。

Here is my most recent attempt:这是我最近的尝试:

SELECT * PRODUCT FROM PRODUCT
INNER JOIN line
ON product.p_code = line.p_code
WHERE sum(line_units) >=10
AND line.p_code = product.p_code;

Error: near "product";错误:靠近“产品”; syntax error语法错误

Any help would be appreciated, Thank you.任何帮助将不胜感激,谢谢。

Looks like you have the table name PRODUCT within the SELECT section.看起来您在SELECT部分中有表名PRODUCT And the sum() needs to happen within the SELECT section along with the extra HAVING clause at the end. sum()需要在SELECT部分以及最后的额外HAVING子句中发生。

SELECT *, sum(line_units) as line_units_sum FROM product
INNER JOIN line ON product.p_code = line.p_code
WHERE line.p_code = product.p_code
HAVING line_units_sum >= 10

The requirement要求

Show all product information from the product table for any product that has sold more than 10 units.显示product表中已售出超过 10 件的任何产品的所有产品信息。

The solution解决方案

Because you only want to build the projection from the product table, and you don't need any column from the line table, you can also use a correlated subquery like the following one:因为您只想从product表构建投影,并且不需要line表中的任何列,所以您还可以使用如下相关的子查询:

SELECT *
FROM product
WHERE 10 < (
    SELECT COUNT(*)
    FROM line
    WHERE line.p_code = product.p_code
)

The database optimizer might choose to use a JOIN internally if the cost of the JOIN is lower than other alternatives.如果 JOIN 的成本低于其他替代方案,则数据库优化器可能会选择在内部使用 JOIN。 So, it does not mean that the query will do row-by-row processing for the outer table records.因此,这并不意味着查询将对外部表记录进行逐行处理。 Only the execution plan can tell how the query is executed by the database engine.只有执行计划可以告诉数据库引擎如何执行查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM