如何在SELECT查询中使用CASE语句赋值?查询报错问题咨询
Let's break down what's going wrong here and get your query working as intended. You're hitting two main issues: a syntax error in how you're defining the column alias and CASE statement, plus a logical mistake in your JOIN type that would have stopped your 'admin' fallback from ever triggering.
1. The Syntax Error Causing the "From keyword not found" Message
Your original code uses function_role = (...) to assign the alias, which isn't valid in standard SQL (especially if you're using Oracle, which throws that specific error). You need to use AS function_role instead.
Additionally, your CASE statement is structured incorrectly. The CASE [column] WHEN [value] format is for matching specific values, not checking conditions like IS NOT NULL. You should use the CASE WHEN [condition] syntax here.
2. The Logical Issue with Your JOIN
You're using an INNER JOIN between team_members and mem_function. This means any team_members row without a matching function_id in mem_function gets dropped entirely—so you'd never hit the ELSE 'admin' branch. Switch to a LEFT JOIN to keep all team_members rows, even when there's no matching mem_function record.
Corrected Query
Here's the fixed version of your subquery, integrated back into your original statement:
LEFT OUTER JOIN ( SELECT tm.item_id AS item_id, -- Clean CASE statement with correct syntax CASE WHEN mf.function_name IS NOT NULL THEN mf.function_name ELSE 'admin' END AS function_role FROM team_members tm -- Use LEFT JOIN to preserve rows without a matching mem_function entry LEFT JOIN mem_function mf ON mf.function_id = tm.function_id ) bnu ON bnu.item_id = p.pro_id
Even Simplified Option
If you want to make this shorter, you can use the COALESCE function, which returns the first non-null value in a list. It does exactly what your CASE statement is trying to do:
LEFT OUTER JOIN ( SELECT tm.item_id AS item_id, COALESCE(mf.function_name, 'admin') AS function_role FROM team_members tm LEFT JOIN mem_function mf ON mf.function_id = tm.function_id ) bnu ON bnu.item_id = p.pro_id
Both versions will correctly assign 'admin' whenever mf.function_name is null, and fix the syntax error that was breaking your query.
内容的提问来源于stack exchange,提问作者KnowNothing

