加入两个选择语句

2021-12-17 00:00:00 join sql mysql

谁能告诉我为什么以下不起作用?它抱怨两个选择之间的连接关键字附近出现语法错误.

Can anyone tell me why the following won't work? It complains of a syntax error near the join key word between the two selects.

SELECT * 
FROM ( select * from orders_products inner JOIN orders ON orders_products.orders_id = orders.orders_id  where products_id = 181) 
as A

join 

SELECT * 
FROM ( select * from orders_products INNER JOIN orders ON orders_products.orders_id = orders.orders_id  where products_id = 180) 
as B

on A.orders_id=B.orders_id

基本上我的第一个 SELECT 从一个表中提取某个产品的所有订单信息,并从另一个表中提取订购的数量并将它们连接在一起.第二个 SELECT 对另一个产品做同样的事情.

Basically my first SELECT pulls all the order info for a certain product from one table and pulls the quantity ordered from another and joins them together. The second SELECT does the same thing for another product.

现在,我有

_______A_________         _______B_________
O_ID P_ID Q O_ID P_ID Q
1 180 3 1 181 11
2 180 9 2 181 6
3 180 5 3 181 3

而且,我想使用另一个连接

And, using another join I want to get


Q_ID P_ID1 Q1 P_ID2 Q2
1 180 3 181 11
2 180 9 181 6
3 180 5 181 3

也许我在这里采取了错误的方法.有什么建议吗?

Maybe I am taking a wrong approach here. Any suggestions?

更新:以下是 RedFilter 指示后对我有用的方法:

UPDATE: Here is what worked for me after pointers by RedFilter:

(SELECT * 
FROM (
SELECT * FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id =181) AS A
LEFT JOIN (
SELECT * FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id =180) AS B ON A.orders_id = B.orders_id
)
UNION (
SELECT * 
FROM (
SELECT * 
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id =181
) AS C
RIGHT JOIN (
SELECT * 
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id =180
) AS D ON C.orders_id = D.orders_id
) 

推荐答案

不确定您要做什么,但您有两个选择子句.改为这样做:

Not sure what you are trying to do, but you have two select clauses. Do this instead:

SELECT * 
FROM ( SELECT * 
       FROM orders_products 
       INNER JOIN orders ON orders_products.orders_id = orders.orders_id 
       WHERE products_id = 181) AS A
JOIN ( SELECT * 
       FROM orders_products 
       INNER JOIN orders ON orders_products.orders_id = orders.orders_id
       WHERE products_id = 180) AS B

ON A.orders_id=B.orders_id

更新:

您可能可以将其简化为这样的:

You could probably reduce it to something like this:

SELECT o.orders_id, 
       op1.products_id, 
       op1.quantity, 
       op2.products_id, 
       op2.quantity
FROM orders o
INNER JOIN orders_products op1 on o.orders_id = op1.orders_id  
INNER JOIN orders_products op2 on o.orders_id = op2.orders_id  
WHERE op1.products_id = 180
AND op2.products_id = 181

相关文章