有谁能告诉我为什么以下不起作用?它抱怨两个选择之间的连接关键字附近有语法错误。
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
对另一个产品做同样的事情。
现在,我有
_______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
而且,使用另一个我想要的连接
Q_ID P_ID1 Q1 P_ID2 Q2
1 180 3 181 11
2 180 9 181 6
3 180 5 181 3
也许我在这里采取了错误的做法。有什么建议吗?
更新: 在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
)
答案 0 :(得分:43)
不确定您要做什么,但您有两个选择条款。这样做:
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
更新
你可能会把它减少到这样:
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
答案 1 :(得分:8)
如果要组合不同的结果集,则应使用UNION。请尝试以下方法:
(SELECT *
FROM ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 181) AS A)
UNION
(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)
答案 2 :(得分:3)
这将做你想要的:
select *
from orders_products
INNER JOIN orders
ON orders_products.orders_id = orders.orders_id
where products_id in (180, 181);
答案 3 :(得分:-1)
SELECT *
FROM
(First_query) AS ONE
LEFT OUTER JOIN
(Second_query ) AS TWO ON ONE.First_query_ID = TWO.Second_Query_ID;