通过CASE语句选择多个值?

时间:2011-03-09 09:55:39

标签: mysql

我有一个带有Owner_ID字段的Vehicle表。此Owner_ID将对应于Customer表中的ID字段或Business表中的ID字段。我希望根据ID所属的表返回不同的值。

我有这样的声明:

SELECT v.Make, v.Model
FROM Vehicle v
LEFT JOIN Customer c ON c.ID = v.Owner_ID
LEFT JOIN Business b ON b.ID = v.Owner_ID

所以说如果Owner_ID = Customer.ID,我想返回客户姓氏,如果Owner_ID = Business_ID,则返回公司名称。我知道我可以使用CASE语句:

SELECT v.Make, v.Model,
    CASE WHEN c.ID IS NOT NULL THEN c.Surname
        WHEN b.ID IS NOT NULL THEN b.Name

但是有没有办法从一个case语句中获取多个值?类似的东西:(我知道这样做完全是错的。)

SELECT v.Make, v.Model,
    CASE WHEN c.ID IS NOT NULL THEN
            SELECT c.Surname, c.Date_Of_Birth
        WHEN b.ID IS NOT NULL THEN
            SELECT b.Name, b.Founded

或者我必须这样做:

SELECT v.Make, v.Model,
    CASE WHEN c.ID IS NOT NULL THEN c.Surname
        WHEN b.ID IS NOT NULL THEN b.Name
    END AS "Name",
    CASE WHEN c.ID IS NOT NULL THEN c.Date_Of_Birth
        WHEN b.ID IS NOT NULL THEN b.Founded
    END AS "DOB/Founded"

3 个答案:

答案 0 :(得分:2)

我认为需要明确查询应该返回哪些列,这不能根据查询而改变。因此,每列必须分解条件。

IF怎么样?在这种情况下可能更容易阅读。

SELECT v.Make, v.Model,
    IF(c.ID IS NOT NULL, c.Surname,       IF(b.ID IS NOT NULL, b.Name,    NULL)) as `Name`
    IF(c.ID IS NOT NULL, c.Date_Of_Birth, IF(b.ID IS NOT NULL, b.Founded, NULL)) as `DOB_Founded`

答案 1 :(得分:2)

没有办法让case表达式的分支跨越多列。

在您的示例中,您可以执行

SELECT v.Make,
       v.Model,
       MAX(COALESCE(c.Surname, b.name)) as name
FROM   Vehicle v
       LEFT JOIN Customer c
         ON c.ID = v.Owner_ID
       LEFT JOIN Business b
         ON b.ID = v.Owner_ID
GROUP  BY v.Owner_ID 

答案 2 :(得分:0)

不确定,但你可以试试这个

SELECT v.Make, v.Model
FROM Vehicle v
LEFT JOIN Customer c ON c.ID = v.Owner_ID
LEFT JOIN Business b ON b.ID = v.Owner_ID 
WHERE c.Surname IS NOT NULL 
OR b.name IS NOT NULL