选择0个值作为现有列名

时间:2019-11-25 08:58:15

标签: sql

嗨,我有2个表,每列3列:

位置

ID | KnownLocationID | Other 1 | 2 | Test 2 | 0 | TestOther

已知位置

ID | Title 1 | KNOWNTest 2 | KNOWNTestOther

我需要提取所有已知位置。如果为0,我需要拉Other

因此,第一个表的预期输出应该带回:

ID | Location 1 | KNOWNTestOther 2 | TestOther

预期产量

3 个答案:

答案 0 :(得分:1)

由于您没有标记询问的SQL,所以我假设它是MySQL。因此,您只需使用IF函数:

SELECT l.id, IF(l.KnownLocationID = 0, l.Other, kl.Title)
FROM Locations AS l
LEFT JOIN KnownLocations AS kl ON kl.ID = l.KnownLocationID

Working Fiddle

答案 1 :(得分:1)

您只需使用CASE

SELECT l.id,
CASE WHEN l.KnownLocationID = 0 THEN l.other ELSE kl.Title END AS Location
FROM Locations AS l
LEFT JOIN KnownLocations AS kl ON kl.ID = l.KnownLocationID

答案 2 :(得分:0)

查询:

SELECT loc.ID, IF(kl.Title IS NULL,loc.Other,kl.Title) AS Location FROM locations loc LEFT JOIN knownlocations kl ON kl.ID = loc. KnownLocationID