简体   繁体   中英

How do I use a select Subquery in MYSQL

I have two databases that I'm trying to transfer data between.

I'm working on getting orders from one to the other right now but I've run into something that I can't figure out the correct way to do it.

Here's the query thus far...

INSERT INTO `NEWTEST`.`Order_LineDetails`

( OrderLineItem_ID, Customer_ID, Order_ID )

SELECT

OrderDetailID,

(    
SELECT o.CustomerID
FROM `OLDTEST`.`Order_Details` od
JOIN `OLDTEST`.`Orders` o ON  o.OrderID = od.OrderID
),

OrderID

FROM `OLDTEST`.`Order_Details`

This is returning an error of '#1242 - Subquery returns more than 1 row'.

The result I'm going for would be to get...

OLDTEST.Order_Details           -> NEWTEST.Order_LineDetails
OLDTEST.Order.CustomerID        -> NEWTEST.Customer_ID
OLDTEST.Order_Details.OrderID   -> NEWTEST.Order_ID

What am I missing?

:::::: EDIT :::::::

This is now correct and works fine.

SELECT

  od.OrderDetailID,
  o.CustomerID,
  od.OrderID

FROM `OrderProcessing`.`Order_Details` od

JOIN `OrderProcessing`.`Orders` o ON o.OrderID = od.OrderID

LIMIT 100

When you use a subquery in the SELECT clause as you did, it must return a single row, hence the error you're getting.

Actually you don't seem to need the subquery here:

INSERT INTO `NEWTEST`.`Order_LineDetails`
SELECT
    od.OrderDetailID,
    o.CustomerID,
    od.OrderID
FROM `OLDTEST`.`Order_Details` od
JOIN `OLDTEST`.`Orders` o ON  o.OrderID = od.OrderID

(Before running that, comment out the INSERT line to make sure it's giving the results you expect).

MySQL subquerys can only contain one result (and apparently yours is returning more). You can add a limit to fix this:

SELECT o.CustomerID
FROM `OLDTEST`.`Order_Details` od
JOIN `OLDTEST`.`Orders` o ON  o.OrderID = od.OrderID LIMIT 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM