Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Select results with specified ID or with null

Tags:

mysql

I have one table:

| ID | ADV_ID | USER_ID |
| 1  |   22   |   NULL  |
| 2  |   22   |    3    |
| 5  |   44   |   NULL  |

and now, I want to select row where adv_id = 22 and user_id = 3. If that row doesn't exist, I want to get row where adv_id = 22 and user_id is null.

I tried in that way:

SELECT * FROM `table` WHERE adv_id = 22 AND (user_id = 3 OR user_id is null)

but this query return two rows - with user_id = NULL and with user_id = 3. I want to get one row - with user_id = 3 or (if not exist), with user_id = NULL.

How I can do it in one query? Thanks.

like image 869
Pavel K Avatar asked Apr 02 '18 14:04

Pavel K


People also ask

How do I select only NULL values in MySQL?

To search for column values that are NULL , you cannot use an expr = NULL test. The following statement returns no rows, because expr = NULL is never true for any expression: mysql> SELECT * FROM my_table WHERE phone = NULL; To look for NULL values, you must use the IS NULL test.

Is NULL in select MySQL?

MySQL IFNULL() FunctionThe IFNULL() function returns a specified value if the expression is NULL. If the expression is NOT NULL, this function returns the expression.

How do I ignore blank cells in SQL?

SELECT column_names FROM table_name WHERE column_name IS NOT NULL; Query: SELECT * FROM Student WHERE Name IS NOT NULL AND Department IS NOT NULL AND Roll_No IS NOT NULL; To exclude the null values from all the columns we used AND operator.


1 Answers

Use conditional aggregation:

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT
        ADV_ID,
        CASE WHEN COUNT(CASE WHEN USER_ID = 3 THEN 1 END) > 0 THEN 3 END USER_ID
    FROM yourTable
) t2
    ON t1.ADV_ID = t2.ADV_ID AND
       ((t1.USER_ID IS NULL AND t2.USER_ID IS NULL) OR (t1.USER_ID = t2.USER_ID))
WHERE
    t1.ADV_ID = 22;

Demo

For an explanation, the subquery I have aliased as t2 aggregates over the ADV_ID, and outputs the value 3 if that value occurs in one or more records, otherwise it outputs NULL. Then, we join this subquery back to your original table on the condition that both USER_ID values are NULL, or, if not, that the two USER_ID values match.

You may modify the demo to see that it generates the output you want for other inputs.

like image 122
Tim Biegeleisen Avatar answered Oct 20 '22 19:10

Tim Biegeleisen