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
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.
Now, I have
_______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?
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
)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…