MySQL SELECT WHERE IN LIST and NOT IN LIST in the same SQL

后端 未结 1 1205
醉酒成梦
醉酒成梦 2021-01-15 22:27

I have this:

    $ids = \"1,2,3,4,5\";
    $sqlQuery = \"SELECT id, moderation_date
                    FROM table_live
                    WHERE id IN (\".$         


        
相关标签:
1条回答
  • 2021-01-15 22:37

    generate an outer join statement so that you get:

    SELECT ids.id, table_live.moderation_date
    FROM (select 1 id union all select 2 union all ....) ids
    LEFT JOIN table_live
    ON ids.id = table_live.id
    

    where ids is a subquery enumerating all the values, something like this:

    $ids = '1,2,3,4,5'
    $subquery = 'select '.str_replace(',', ' id union all select ', $ids).''
    $sql = "SELECT ids.id, table_live.moderation_date
    FROM ($subquery) ids
    LEFT JOIN table_live
    ON ids.id = table_live.id"
    

    be sure to select ids.id, not table_live.id. That way, the ids will always show up, and the moderation_date only if the corresponding row exists in table_live.

    Another approach would be to keep the query as you had it, store the result in an array, and then merge the arrays in php so that you retain all keys, and fill in the values only where the key matches in both arrays.

    I am not really sure what kind of db library you're using so I don't know how to obtain an array of the resultset, but suppose you would have stored the rows in a php array, using a string representation of the id as key, and the date as value, then this code should do the trick:

    $items = array(
        '1' => NULL
    ,   '2' => NULL
    ,   ...
    ); 
    //note: use string keys in order to merge!!
    $result = array_merge($items, $resultset);
    

    see: http://php.net/manual/en/function.array-merge.php

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