通过CASE语句选择多个值?
我有一个车辆表,其中有一个Owner_ID字段。 此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"
不,没有办法让一个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
我认为它需要清楚查询应该返回哪些列,并且这不能根据查询而改变。 所以必须按每列分解条件。
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`
不确定,但你可以试试这个
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
链接地址: http://www.djcxy.com/p/51407.html