Home > Database > Mysql Tutorial > Can I Use a CASE Statement in a JOIN Condition?

Can I Use a CASE Statement in a JOIN Condition?

Mary-Kate Olsen
Release: 2025-01-20 07:31:09
Original
279 people have browsed it

Can I Use a CASE Statement in a JOIN Condition?

Can the CASE statement be used in JOIN conditions?

When trying to join tables based on the value of a column in the sys.allocation_units table, the following code produces a syntax error:

<code class="language-sql">SELECT  *
FROM sys.indexes i
JOIN sys.partitions p
    ON i.index_id = p.index_id 
JOIN sys.allocation_units a
    ON CASE
       WHEN a.type IN (1, 3)
           THEN a.container_id = p.hobt_id 
       WHEN a.type IN (2)
           THEN a.container_id = p.partition_id
       END </code>
Copy after login

Explanation of error reason:

CASE expression returns a single value, not an equality expression. In this example, the result of the CASE expression needs to be compared to a constant (such as 1) to determine whether the condition is true.

Corrected code:

<code class="language-sql">SELECT  * 
FROM sys.indexes i 
JOIN sys.partitions p 
    ON i.index_id = p.index_id  
JOIN sys.allocation_units a 
    ON CASE 
       WHEN a.type IN (1, 3) AND a.container_id = p.hobt_id THEN 1
       WHEN a.type IN (2) AND a.container_id = p.partition_id THEN 1
       ELSE 0
       END = 1</code>
Copy after login

This code compares the result of the CASE expression with 1 and returns the row where the condition is true.

The above is the detailed content of Can I Use a CASE Statement in a JOIN Condition?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template