嗨我得到“错误代码:1146。下一个sql代码上的表'sakila.t'不存在。”
select distinct address.address
from (
select inventory.store_id,
count(inventory.inventory_id) as num_of_items
from inventory
group by inventory.store_id
) as T,
address,
store,
where T.num_of_items <= all (select num_of_items from T)
and store.store_id = T.store_id
and store.address_id = address.address_id
来自评论这应该返回其广告资源中商品数量最少的商店的地址。
我认为它是因为我试图从子查询中获取T中的信息,而T是一个变量而且在sakila数据库中没有定义。这是问题吗?如果是,为什么?如果没有,请告诉我代码有什么问题。感谢。
答案 0 :(得分:0)
要使这种SQL查询起作用,您需要分解任务。
首先,您要确定每家商店包含多少商品。这很简单,我认为你做对了。
select inventory.store_id,
count(inventory.inventory_id) as num_of_items
from inventory
group by inventory.store_id
接下来,您要确定哪个商店的商品数量最少。你是这样做的。
select inventory.store_id,
count(inventory.inventory_id) as num_of_items
from inventory
group by inventory.store_id
order by count(inventory.inventory_id) ASC
limit 1
接下来,将其嵌入查询中,查询将查找描述商店的数据。
select address.address
from (
select inventory.store_id,
count(inventory.inventory_id) as num_of_items
from inventory
group by inventory.store_id
order by count(inventory.inventory_id)
limit 1
) as T
join store on T.store_id = store.store_id
join address on store.address_id = address.address_id
这就是你需要的结果。这里的技巧是使用聚合子查询(count() ... order by ... limit 1) to find the particular item you need, then to use a bunch of
join`子句来收集显示有关您找到的项目的数据。
当您调试并解决此类问题时,您可以从最简单的查询开始,逐步构建查询。