简体   繁体   English

从子查询中选择列

[英]Selecting from a subquery into a column

So say I've got a table called orders with a column zip_code and a table called provinces . 假设我有一个名为orders的表,该表具有一列zip_code和一个名为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). provinces具有字段namestarting_zipending_zip (以指示开始和结束zip之间的所有邮政编码均属于该省)。

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. 我真的不明白为什么应该在FROM语句中。 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语句如下所示:

FROM orders

But the WHERE clause look like this: 但是WHERE子句如下所示:

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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