错误#1241 SQL查询

时间:2018-06-11 17:47:06

标签: mysql sql

我一直收到错误代码#1241。我一直在寻找答案,但我无法找到帮助我的答案。

这是我的代码:

SELECT name, address, city, phone  
FROM customer
WHERE customer.ID IN (
    SELECT customer.ID, COUNT(*) AS amount_reservations 
    FROM customer, (
        SELECT ID 
        FROM customer, reservations 
        WHERE rent_time = 'weekend' AND 
        ID = customer_ID
    ) AS foo 
    WHERE customer.ID = foo.ID 
    GROUP BY customer.ID 
    HAVING amount_reservations > 1
)

3 个答案:

答案 0 :(得分:3)

子查询SELECT customer.ID, COUNT(*) AS amount_reservations应该有一个SINGLE列,而不是两列。

将其更改为:

SELECT name, address, city, phone  
  FROM customer  
  WHERE customer.ID IN (
    SELECT customer.ID
      FROM customer, (
        SELECT ID FROM customer, reservations 
          WHERE rent_time = 'weekend' AND ID = customer_ID
        ) AS foo 
      WHERE customer.ID = foo.ID 
      GROUP BY customer.ID HAVING count(*) > 1
    )

答案 1 :(得分:1)

我强烈建议您重写查询。删除子查询 - 不需要它们。然后使用explicit joins代替逗号。

select c.id, c.name, c.address, c.city, c.phone  
from customer c
    join reservations r on c.id = r.customer_id
where r.rent_time = 'weekend'
group by c.id, c.name, c.address, c.city, c.phone  
having count(*) > 1

答案 2 :(得分:1)

如果您想使用in,您可以从根本上简化查询:

SELECT c.name, c.address, c.city, c.phone  
FROM customer c
WHERE c.ID IN (SELECT r.customer_id
               FROM reservations r
               WHERE r.rent_time = 'weekend' 
               GROUP BY r.customer_id
               HAVING COUNT(*) > 1
              ) ;

注意:

  • 从不FROM子句中使用逗号。始终使用正确,明确,标准的JOIN语法。
  • 对所有列引用使用表别名和限定列名。
  • 您在子查询中不需要JOIN,因为您在预订表中有客户ID。