正如this线程中所讨论的那样,from子句中的子查询不是必需的并且会产生笛卡尔积,但会出现新的问题。
SELECT customer.customer_name
,orders.order_date
,order_line.num_ordered
,order_line.quoted_price
,part.descript
,amt_billed
FROM (SELECT order_line.num_ordered*part.price AS amt_billed
FROM order_line
JOIN part
ON order_line.part_num = part.part_num
) billed
,customer
JOIN orders
ON customer.customer_num = orders.customer_num
JOIN order_line
ON orders.order_num = order_line.order_num
JOIN part
ON order_line.part_num = part.part_num;
让我们说我决定在from子句中使用子查询。如果您阅读了注释,@ GeorgeCampos建议我使用AS
建立别名,然后在子查询和现有表之间编写连接。
当我在子查询和别名AS
之间放置billed
时,我得到ORA-00933: SQL command not properly ended
。删除AS
并运行它不会返回错误,但会返回笛卡尔积。
此外,我尝试使用join
别名的任何billed
都会返回ORA-00942: table or view does not exist
。
总之,如果我决定将子查询保留在from子句中,我想知道如何写这个。
我使用的是Oracle 11g pl / sql。
更新
此:
SELECT customer.customer_name
,orders.order_date
,order_line.num_ordered
,order_line.quoted_price
,part.descript
,amt_billed
FROM (SELECT order_line.num_ordered*part.price AS amt_billed, orders.order_num
FROM order_line
JOIN part
ON order_line.part_num = part.part_num
) AS billed
JOIN customer
ON customer.customer_num = orders.customer_num
JOIN billed
ON orders.order_num = order_line.order_num
JOIN orders
ON customer.customer_num = orders.customer_num
JOIN order_line
ON orders.order_num = order_line.order_num
JOIN part
ON order_line.part_num = part.part_num;
返回:
) AS billed
*
ERROR at line 11:
ORA-00933: SQL command not properly ended
在第11行删除AS
会返回:
JOIN billed
*
ERROR at line 14:
ORA-00942: table or view does not exist
更新
感谢@GordonLinoff,我向您呈现最终代码!
SELECT customer.customer_name
,orders.order_date
,order_line.num_ordered
,order_line.quoted_price
,amt_billed
,part.descript
FROM customer
JOIN orders
ON customer.customer_num = orders.customer_num
JOIN order_line
ON orders.order_num = order_line.order_num
JOIN part
ON order_line.part_num = part.part_num
JOIN (SELECT DISTINCT order_line.part_num
,order_line.num_ordered*part.price AS amt_billed
FROM order_line
JOIN part
ON order_line.part_num = part.part_num
) billed
ON billed.part_num = order_line.part_num
ORDER BY customer.customer_name, orders.order_date;
我按照他说的做了,并删除了对客户的冗余连接。我还必须换掉子选择的内容。如果我坚持使用num_ordered
,只要订购了一个零件,行就会重复自己。
答案 0 :(得分:1)
Oracle不支持as
表别名。所以:
FROM (SELECT order_line.num_ordered*part.price AS amt_billed, orders.order_num
FROM order_line JOIN
part
ON order_line.part_num = part.part_num
) billed JOIN
--------^
Customer
. . .
编辑:
您不需要重复 billed
。你想要这样的东西:
FROM customer JOIN
orders
ON customer.customer_num = orders.customer_num JOIN
order_line
ON orders.order_num = order_line.order_num JOIN
part
ON order_line.part_num = part.part_num JOIN
(SELECT order_line.order_num, order_line.num_ordered*part.price AS amt_billed
FROM order_line JOIN
part
ON order_line.part_num = part.part_num
) billed
ON billed.order_num = order.order_num;