0

I'm trying to create query with user_id parameter that would select one row per article_id where row with set user_id has priority. For example:

If user_id = 1, rows with id 2, 3, 4 should be selected.

If user_id = 2, rows with id 1, 3, 5 should be selected.

If user_id = 17, rows with id 1, 3, 4 should be selected.

Please consider pair (user_id, article_id) unique.

id   user_id   article_id
1    null      8
2    1         8
3    null      9
4    null      10
5    2         10
2
  • Please edit your question to add expected output Commented Sep 30, 2018 at 4:08
  • Hey @MadhurBhaiya, I did it when created Question, there are 3 different examples with expected outputs. Commented Sep 30, 2018 at 5:51

1 Answer 1

1

You can use this query:

SELECT *
FROM articles a1
WHERE user_id = 1 OR
    user_id IS NULL AND NOT EXISTS(SELECT * FROM articles a2 WHERE a2.article_id = a1.article_id AND a2.user_id = 1)
ORDER BY user_id IS NULL

This will find all the articles which match user_id = 1, or a NULL user_id where there was not a matching entry with the requested user_id. The results are ordered by user_id IS NULL which will be 0 for an article which matches the user_id, and 1 for an article where user_id is NULL, thus prioritising the actual matches on user_id.

Output (for user_id=1):

id  user_id     article_id
2   1           8
3   (null)      9
4   (null)      10

Output (for user_id=2):

id  user_id     article_id
5   2           10
1   (null)      8
3   (null)      9

Output (for user_id=17):

id  user_id     article_id
1   (null)      8
3   (null)      9
4   (null)      10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.