gpt4 book ai didi

mysql - 加入两个选择语句

转载 作者:IT老高 更新时间:2023-10-29 00:01:47 26 4
gpt4 key购买 nike

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

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

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
)

最佳答案

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

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

关于mysql - 加入两个选择语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6035901/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com