MySQL query where JOIN depends on CASE

前端 未结 2 1599
轮回少年
轮回少年 2020-12-20 13:27

As I am now aware, CASE can be used only in WHERE context. Though, I need to use different table depending on column value. What I\'ve tried looks like this:

相关标签:
2条回答
  • 2020-12-20 13:47

    It probably needs tweaking to return the correct results but I hope you get the idea:

    SELECT ft1.task, COUNT(ft1.id) AS count
    FROM feed_tasks ft1
    LEFT JOIN pages p1 ON ft1.type=1 AND p1.id = ft1.reference_id
    LEFT JOIN urls u1 ON ft1.type=2 AND u1.id = ft1.reference_id
    WHERE COALESCE(p1.id, u1.id) IS NOT NULL
    AND ft1.account_id IS NOT NULL
    AND a1.user_id = :user_id
    

    Edit:

    A little note about CASE...END. Your original code does not run because, unlike PHP or JavaScript, the SQL CASE is not a flow control structure that allows to choose which part of the code will run. Instead, it returns an expression. So you can do this:

    SELECT CASE
        WHEN foo<0 THEN 'Yes'
        ELSE 'No'
    END AS is_negative
    FROM bar
    

    ... but not this:

    -- Invalid
    CASE 
        WHEN foo<0 THEN SELECT 'Yes' AS is_negative
        ELSE SELECT 'No' AS is_negative
    END
    FROM bar
    
    0 讨论(0)
  • 2020-12-20 13:55

    Use outer joins on both tables and move the CASE inside your COUNT:

    SELECT
        ft1.task,
        COUNT(case ft1.id when 1 then p1.id when 3 then u1.id end) as count
    FROM feed_tasks ft1
    LEFT JOIN pages p1 ON p1.id = ft1.reference_id
    LEFT JOIN urls u1 ON u1.id = ft1.reference_id
    WHERE ft1.account_id IS NOT NULL
    AND a1.user_id = {$db->quote($user['id'])}
    

    Non-hits for the CASE will give a null id and won't be counted.

    Note: Table a1 is in your where clause, but doesn't seem to be a selected table

    0 讨论(0)
提交回复
热议问题