[英]MySQL - Select row if field has value, otherwise select with null value
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. 我正在尝试使用user_id参数创建查询,该查询将为每个article_id选择一行,其中设置了user_id的行具有优先级。 For example: 例如:
If user_id = 1, rows with id 2, 3, 4 should be selected. 如果user_id = 1,则应选择ID为2、3、4的行。
If user_id = 2, rows with id 1, 3, 5 should be selected. 如果user_id = 2,则应选择ID为1、3、5的行。
If user_id = 17, rows with id 1, 3, 4 should be selected. 如果user_id = 17,则应选择ID为1、3、4的行。
Please consider pair (user_id, article_id) unique. 请考虑一对(user_id,article_id)唯一。
id user_id article_id
1 null 8
2 1 8
3 null 9
4 null 10
5 2 10
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
. 这将找到所有与user_id
= 1匹配的文章,或者在没有与所请求的user_id
匹配的条目的情况下为NULL
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
. 结果按user_id IS NULL
排序,对于与user_id
匹配的文章,该值为0,对于user_id
为NULL的文章,其值为1,因此优先考虑与user_id
的实际匹配。
Output (for user_id=1
): 输出(对于user_id=1
):
id user_id article_id
2 1 8
3 (null) 9
4 (null) 10
Output (for user_id=2
): 输出(对于user_id=2
):
id user_id article_id
5 2 10
1 (null) 8
3 (null) 9
Output (for user_id=17
): 输出(对于user_id=17
):
id user_id article_id
1 (null) 8
3 (null) 9
4 (null) 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.