【问题标题】:Write a query to find the full names of customers who have rented sci-fi movies more than 5 times. Arrange these names in the alphabetical order编写查询,查找租借科幻电影 5 次以上的客户的全名。按字母顺序排列这些名称
【发布时间】:2020-10-03 11:46:57
【问题描述】:

你好,下面是我的代码

数据库:https://dev.mysql.com/doc/sakila/en/sakila-structure.html

select concat(first_name,' ',last_name) from
customer where customer_id in (
select customer_id from (
select customer_id, count(rental_id) as num
from 
category 
inner join film_category using(category_id) 
inner join film using(film_id) 
inner join inventory using(film_id) 
inner join rental using (inventory_id)
where name='Sci-Fi'
group by customer_id, rental_id)
where num > 5)T)

当我执行时,我收到以下错误

ERROR 1248 (42000) at line 2: Every derived table must have its own alias

预期结果是"full names of customers who have rented sci-fi movies more than 5 times. Arrange these names in the alphabetical order"

你能告诉我我做错了什么吗?

【问题讨论】:

  • use text, not images/links, for text--including tables & ERDs。转述或引用其他文本。只提供您需要的东西并将其与您的问题联系起来。仅将图像用于无法表达为文本或增强文本的内容。无法搜索或剪切和粘贴图像。在图像中包含图例/键和说明。此外,链接死了。使用编辑功能插入图像/链接。让您的帖子自成一体。
  • 请在代码问题中给出minimal reproducible example--cut & paste & runnable code,包括最小的代表性示例输入作为代码;期望和实际输出(包括逐字错误消息);标签和版本;明确的规范和解释。给出尽可能少的代码,即您显示的代码可以通过您显示的代码扩展为不正常的代码。 (调试基础。)对于包含 DBMS 和 DDL(包括约束和索引)和输入为格式化为表的代码的 SQL。 How to Ask 暂停整体目标的工作,将代码砍到第一个表达式,没有给出你期望的内容,说出你期望的内容和原因。

标签: mysql sql join select group-by


【解决方案1】:

欢迎来到 SO!

首先,您似乎有 3 个打开的 ( 括号和 4 个关闭的 ) 括号。您应该删除最后一个括号,以便平衡括号。

之后,您希望将别名应用于最深层次的查询。 (类似问题:What is the error “Every derived table must have its own alias” in MySQL?)你有...

where name='Sci-Fi'
group by customer_id, rental_id)
where num > 5)T)

你可能想要...

where name='Sci-Fi'
group by customer_id, rental_id) AS T
where num > 5)

(不要忘记,不需要那个额外的结束括号,所以你可以看到我删除了它。它可能是你拥有的更大查询的一部分,但它对问题中的独立代码没有帮助.)

这将停止您看到的即时错误。至少,现在在我的数据库上,我看到的错误是:ERROR 1146 (42S02): Table 'db.customer' doesn't exist

【讨论】:

  • 谢谢您根据您提到的更改接受了代码
【解决方案2】:
select concat(first_name, ' ', last_name) as Customer_name
from category
inner join film_category
using (category_id)
inner join film
using (film_id)
inner join inventory
using (film_id)
inner join rental
using (inventory_id)
inner join customer
using (customer_id)
where name = 'Sci-Fi'
group by Customer_name
having count(rental_id) > 3
order by Customer_name;

【讨论】:

  • 感谢您的回答,但它只包含代码,所以您能否更新它并提供一些解释以及您的代码?
【解决方案3】:
select concat(first_name,' ',last_name) as customer_name from customer
inner join rental 
using(customer_id)
inner join inventory 
using(inventory_id)
inner join film 
using(film_id)
inner join film_category
using(film_id)
inner join category
using(category_id)
where name in ('sci-fi') 
group by customer_name
having count(rental_id) > 2
order by customer_name

【讨论】:

  • 感谢您的回答,但它只包含代码,所以您能否更新它并提供一些解释以及您的代码?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-02
  • 1970-01-01
  • 2016-07-22
  • 2011-01-07
  • 1970-01-01
  • 2021-07-18
相关资源
最近更新 更多