2014-04-30 335 views
0

我有一個客戶下表:與case語句SELECT語句

+------------+-------------+------+-----+---------+----------------+ 
| Field  | Type  | Null | Key | Default | Extra   | 
+------------+-------------+------+-----+---------+----------------+ 
| id   | int(11)  | NO | PRI | NULL | auto_increment | 
| first  | varchar(45) | YES |  | NULL |    | 
| last  | varchar(45) | YES |  | NULL |    | 
| password | varchar(45) | NO |  | NULL |    | 
| contact_id | int(11)  | NO | PRI | NULL |    | 
| address_id | int(11)  | NO | PRI | NULL |    | 
+------------+-------------+------+-----+---------+----------------+ 

並任命下列結構:

+-------------+------------+------+-----+---------+----------------+ 
| Field  | Type  | Null | Key | Default | Extra   | 
+-------------+------------+------+-----+---------+----------------+ 
| id   | int(11) | NO | PRI | NULL | auto_increment | 
| time  | datetime | NO |  | NULL |    | 
| cancelled | tinyint(1) | YES |  | 0  |    | 
| confirmed | tinyint(1) | YES |  | 0  |    | 
| customer_id | int(11) | NO | PRI | NULL |    | 
+-------------+------------+------+-----+---------+----------------+ 

我想用一個查詢來獲取客戶信息,如果他們有預約信息,那麼它會查詢它,否則它不會。

我嘗試使用以下命令:

CASE 
    WHEN (SELECT count(a.id) FROM appointment 
      INNER JOIN customer c ON a.customer_id = c.id) 
     THEN (SELECT c.first, c.last, c.id, a.id FROM appointent 
       INNER JOIN customer c ON a.customer_id = c.id) 
    ELSE 
     (SELECT c.first, c.last, c.id FROM customer) 
END; 

你有什麼建議嗎?

回答

2

怎麼樣

SELECT * FROM Customer c LEFT JOIN Appointment a ON a.CustomerId = c.Id 
+0

蕩你的答案的工作,這是一個容易得多比我做的。謝謝 –

+0

@ user3037661你也可以做 select * from customer where id in(select customer_id from appointment where cancelled = 0) – PaulG

+0

保持簡單(tm) –

1

你可以做兩個查詢和UNION他們。

SELECT c.first, c.last, c.id, a.id FROM appointent a 
       INNER JOIN customer c ON a.customer_id = c.id 
UNION 
SELECT c.first, c.last, c.id, null FROM customer c 

或外部連接,其中a.id將與空,如果有在參加比賽沒有被填充。

SELECT c.first, c.last, c.id, a.id FROM customer c 
       OUTER JOIN appointent a ON a.customer_id = c.id 
0

按我的茲德拉夫科的答案評論,你可以也用:

select * from customer where id in (select customer_id from appointment where cancelled = 0) 

這將允許你在一個不錯的方式進行篩選。

您還可以過濾茲德拉夫科的回答是這樣的:

SELECT * FROM Customer c LEFT JOIN Appointment a ON a.CustomerId = c.Id 
WHERE a.cancelled 0 and a.confirmed = 1