带有case语句的SELECT语句

时间:2014-04-30 19:39:51

标签: mysql sql

我有以下表格供客户使用:

+------------+-------------+------+-----+---------+----------------+
| 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;

你有什么建议吗?

3 个答案:

答案 0 :(得分:2)

怎么样

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

答案 1 :(得分: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将填充为null。

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

答案 2 :(得分:0)

根据我对Zdravko答案的评论,您也可以使用:

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

这将允许您以一种很好的方式过滤。

你也可以像这样过滤Zdravko的答案:

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