2010-07-03 14 views
1

我需要選擇一個列表,顯示每個已租用汽車的客戶的客戶編號,標題,名字和姓氏,按客戶姓氏的字母順序排列以及計數他們每個人的預訂都已放置。我需要幫助使用計數作爲查詢

我已經完成了第一部分,但不知道在哪裏放置預訂的數量。

下面是表是

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, customer_title, Customer_fname, customer_sname 
from customer 
where customer_id in 
(select customer_id from car_booking) 
order by customer_sname asc 

感謝

回答

0

在SQL Server中,我會使用:

select c.customer_id, 
     c.customer_title,   
     c.customer_fname, 
     c.customer_sname, 
     count (*) 
    from cutomer c, 
     car_booking cb 
where cb.customer_id = c.customer_id 
group by c.customer_id, 
      c.customer_title, 
      c.customer_fname, 
      c.customer_sname 

不密切熟悉MySQL,所以它可能會pl有點不同,但這是一般的想法。

+1

我不使用此語法的唯一原因是它使用theta連接(即隱式連接)。 – 2010-07-04 00:21:55

1

這將需要使用聚集函數(COUNT),GROUP BY子句和LEFT的JOIN到CAR_BOOKING表:

SELECT c.customer_id, c.customer_title, c.customer_fname, c.customer_sname, 
      COALESCE(COUNT(*), 0) AS num_bookings 
    FROM CUSTOMER c 
LEFT JOIN CAR_BOOKING cb ON cb.customer_id = c.customer_id 
GROUP BY c.customer_id, c.customer_title, c.customer_fname, c.customer_sname 
ORDER BY c.customer_sname 

因爲有不包裹在像COUNT聚合函數列,那些列需要在GROUP BY子句中定義。

我對CAR_BOOKINGS表使用了一個左外部連接來返回沒有任何預訂的客戶 - 這些記錄將顯示爲0,作爲num_booking列中的值。您可以在查詢中省略LEFT關鍵字,以僅返回客戶預訂計數&。 COALESCE是將空值轉換爲所需值的標準函數 - 在這種情況下,計數爲空...

0
select customer.customer_id, customer.customer_title, customer.customer_fname, customer.customer_sname, count(*) as Bookings 
from customer JOIN car_booking ON customer.customer_id = car_booking.customer_id 
GROUP BY customer.customer_id, customer.customer_title, customer.Customer_fname, customer.customer_sname 
order by customer_sname asc 
+0

謝謝大家,我有什麼是customer_id的,由於某種原因沒有預訂汽車租賃。它顯示了6輛車已經預訂,但是當我運行它時,它顯示了大部分的customer_id。還有什麼想法?謝謝 – user380603 2010-07-04 00:00:28

+1

@skygirl:查看我答案的最後一段,解釋爲什麼您會看到您所做的輸出,以及如何在必要時更改查詢以進行糾正。 – 2010-07-04 00:14:04

+0

@skygirl嘿......我傾向於把這個不用運行測試用例搞砸了。我認爲在這裏左連接不正確。一個簡單的JOIN應該是正確的。我會更新我的答案。 – 2010-07-04 00:19:35