So say I've got a table called orders
with a column zip_code
and a table called provinces
. provinces
has the fields name
, starting_zip
and ending_zip
(to indicate that all zip codes between starting and ending zip pertain to this province).
I need to select thousands of orders and include the name of the province they are to ship to. I've tried something like this:
SELECT orders.*, p.name
FROM orders, (SELECT name FROM provinces
WHERE order.zip_code >= provinces.starting_zip
AND order.zip_code <= provinces.ending_zip LIMIT 1) p
WHERE...
I also tried:
SELECT orders.*, p.name
FROM orders
JOIN (SELECT name FROM provinces
WHERE order.zip_code >= provinces.starting_zip
AND order.zip_code <= provinces.ending_zip LIMIT 1) p
WHERE...
Also:
SELECT orders.*, (SELECT name FROM provinces
WHERE order.zip_code >= provinces.starting_zip
AND order.zip_code <= provinces.ending_zip LIMIT 1) as name
FROM orders
WHERE...
No matter what I do though, I get an error like:
"Unknown column 'order.zip_code' in 'where clause'
It makes sense that the subselect wouldn't have the scope to access info from the main select, but any idea how I could get this to work?
Why don't you do it like this?
SELECT orders.*,
(
SELECT name
FROM provinces
WHERE orders.zip_code >= provinces.starting_zip
AND orders.zip_code <= provinces.ending_zip
LIMIT 1
) as name
FROM orders
WHERE...
I do not really see why this should be in the FROM
statement. You are anyway selecting just the name column
Update
Did you see that I changed the tables name in the subquery? The FROM
statement looks like this:
FROM orders
But the WHERE
clause look like this:
WHERE order.zip_code >= provinces.starting_zip
AND order.zip_code <= provinces.ending_zip
I have changed it in the query to this:
WHERE orders.zip_code >= provinces.starting_zip
AND orders.zip_code <= provinces.ending_zip
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.