使用NOT IN并使用查询计数

时间:2010-07-04 12:19:55

标签: sql mysql

对未租用汽车的客户数量有问题

create table customer
(customer_id  char(4) primary key not null,
customer_sname varchar (30) not null,
customer_fname varchar (30) not null,
customer_title varchar (6) not null,
customer_address1 varchar (35) not null,
customer_address2 varchar (35) null,
customer_postcode varchar (25) null,
customer_phone varchar (30) null,
customer_email varchar (40) null,
customer_di varchar (40) not null)
ENGINE=InnoDB;

create table car_booking
(booking_id INTEGER AUTO_INCREMENT primary key not null,
car_id char (4) not null,
customer_id char (4)  not null,
hire_sdate date not null,
hire_edate date not null)
engine=innodb;

这似乎不起作用

SELECT customer_id count(*) 
FROM customer
WHERE customer_id not IN
(SELECT booking_id FROM car_booking

帮帮我:-(

3 个答案:

答案 0 :(得分:2)

两个错误:

  • 您的select语句不应包含客户编号和计数。
  • 您的子选择是选择预订ID而不是客户ID。

试试这个:

SELECT count(*) 
FROM customer
WHERE customer_id NOT IN
(SELECT customer_id FROM car_booking)

答案 1 :(得分:2)

这也应该有用。 IMO它比子查询更好。

SELECT COUNT(*)
FROM customer
LEFT JOIN car_booking
ON customer.customer_id = car_booking.customer_id
WHERE car_booking.customer_id IS NULL

编辑:解释。

LEFT JOIN将引入表客户的所有记录,即使是那些没有car_booking记录的记录。同时,在联接的结果集中,对于客户中没有car_booking条目的所有条目,car_booking.customer_id将为NULL。 WHERE子句仅指定这些行,COUNT(*)计数。

答案 2 :(得分:0)

你错过了逗号和GROUP BY条款;它应该是:

SELECT customer_id, count(*) 
FROM customer
WHERE customer_id not IN
(SELECT booking_id FROM car_booking)
GROUP BY customer_id