我需要从一个乐队列表中显示键盘播放器,我已经能够使用以下SQL:
SELECT BAND.NAME AS Band_Name, KBPLAYER.NAME AS Keyboard_Player
FROM BAND
FULL OUTER JOIN (
SELECT M.NAME, MO.BID
FROM MEMBEROF MO, MEMBER M
WHERE MO.INSTRUMENT='keyboards'
AND M.MID=MO.MID
) KBPLAYER
ON BAND.BID=KBPLAYER.BID
ORDER BY BAND.NAME, KBPLAYER.NAME
以上查询显示该乐队中所有乐队和键盘播放器(如果有)的名称,但我还想为那些没有键盘手的乐队显示“No KeyBoard Players”。我怎样才能做到这一点?如果您需要我提供表格结构的详细信息,请告诉我。
更新:请注意,我无法使用任何SQL3 procedures
(COALESCE, CASE, IF..ELSE
)。它需要严格遵守SQL3标准。
答案 0 :(得分:13)
使用coalesce功能。此函数返回其中第一个非null的参数。例如:
COALESCE(KBPLAYER.NAME,'No KeyBoard Players') AS Keyboard_Player
答案 1 :(得分:2)
我决定采用不同的方式,因为我没有使用上述SQL。如果有人建议用上面的SQL设置约束,我将不胜感激。
SELECT
band.name AS Band_Name, 'NULL' AS Keyboard_Player
FROM
memberof
INNER JOIN
member
ON
memberof.mid = member.mid
FULL JOIN
band
ON
memberof.bid = band.bid
AND
instrument = 'keyboards'
WHERE
member.name IS NULL
UNION
SELECT
band.name AS Band_Name, member.name AS Keyboard_Player
FROM
memberof
INNER JOIN
member
ON
memberof.mid = member.mid
FULL JOIN
band
ON
memberof.bid = band.bid
WHERE
instrument = 'keyboards'
答案 2 :(得分:1)
根据你的评论将空字符串替换为某些文本,简单的解决方案是使用如下的case语句。
SELECT BAND.NAME AS Band_Name,
CASE WHEN KBPLAYER.NAME = '' THEN 'No Player' ELSE KBPLAYER.NAME END AS Keyboard_Player
FROM BAND
FULL OUTER JOIN (
SELECT M.NAME, MO.BID
FROM MEMBEROF MO, MEMBER M
WHERE MO.INSTRUMENT='keyboards'
AND M.MID=MO.MID
) KBPLAYER
ON BAND.BID=KBPLAYER.BID
ORDER BY BAND.NAME, KBPLAYER.NAME
答案 3 :(得分:0)
试试这个......
SELECT BAND.NAME AS Band_Name,
ISNULL(NULLIF(KBPLAYER.NAME,''),'No KeyBoard Players') AS Keyboard_Player
FROM BAND
FULL OUTER JOIN (
SELECT M.NAME, MO.BID
FROM MEMBEROF MO, MEMBER M
WHERE MO.INSTRUMENT='keyboards'
AND M.MID=MO.MID
) KBPLAYER
ON BAND.BID=KBPLAYER.BID
ORDER BY BAND.NAME, KBPLAYER.NAME
答案 4 :(得分:-1)
如果允许使用NVL,则以下情况应该有效。
NVL(KBPLAYER.NAME, 'No KeyBoard Players')