Avoiding "column does not exist" Errors When Using Aliases in PostgreSQL WHERE Clauses
PostgreSQL クエリは、WHERE
句内でエイリアスを使用すると、エイリアスが SELECT
リストで定義されている場合でも、「列が存在しません」エラーをスローすることがあります。 This happens because the WHERE
clause is processed before the SELECT
list, meaning the alias isn't yet recognized.
To overcome this, use a WITH
clause (also known as a Common Table Expression or CTE). A WITH
clause creates a temporary named result set, allowing you to reference the alias within the main query.
Here's an example illustrating the solution:
<code class="language-sql">WITH jobs_with_lead_state AS ( SELECT jobs.*, CASE WHEN lead_informations.state IS NOT NULL THEN lead_informations.state ELSE 'NEW' END AS lead_state FROM jobs LEFT JOIN lead_informations ON lead_informations.job_id = jobs.id AND lead_informations.mechanic_id = 3 ) SELECT * FROM jobs_with_lead_state WHERE lead_state = 'NEW';</code>
This revised query defines a CTE named jobs_with_lead_state
. The CTE performs the initial SELECT
and JOIN
operations, generating the lead_state
alias. The main query then uses this CTE, allowing the WHERE
clause to correctly reference lead_state
. This approach avoids the error by ensuring the alias is available during WHERE
clause evaluation.
以上がPostgreSQL の WHERE 句でエラーなくエイリアスを使用する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。