简体   繁体   English

有效地将两个选择查询组合为一个

[英]Combining two select queries into one efficiently

user 用户

id   |  name
1    |  A
2    |  B

article 文章

id   | title | descritption
1    | wx    | xyz
2    | yz    | abc

article_rating article_rating

article_id(article->id)  |  given_by(user->id)  |  given_rating
   1                              2                  4
   2                              1                  3

saved_article 保存的文章

article_id(article->id)  |  saved_by(user->id) 
   1                              2            

I'm changing some buttons and icons depending on whether a user has rated/ saved an article or not. 我要根据用户是否对文章进行评分/保存来更改一些按钮和图标。 I'm using two select queries for that: 我为此使用两个选择查询:

rated or not 额定与否

SELECT given_rating as rating 
FROM article_rating 
WHERE  given_by=? AND article_id=?

saved or not 是否保存

SELECT saved_by as saved 
FROM saved_article 
WHERE  saved_by=? AND article_id=?

So my question is how can i combine both into one mysql query efficiently?? 所以我的问题是如何将两者有效地组合成一个mysql查询?

Well you could try to write a single query based on a union of the two tables, eg 好吧,您可以尝试根据两个表的并集编写单个查询,例如

SELECT val, source
FROM
(
    SELECT NULL AS saved_by, given_by, given_rating AS val, 'given_rating' AS source
    FROM article_rating
    UNION ALL
    SELECT NULL, NULL AS given_by, saved_by, 'saved_by'
    FROM saved_article
) t
WHERE
    (source = 'given_rating' AND given_by = ? AND article_id = ?) OR
    (source = 'saved_by' AND (saved_by = ? OR saved_by IS NULL) AND article_id = ?);

I use a common trick here, which is to introduce a computed column source into the union query. 我在这里使用了一个常见的技巧,该技巧是将计算的列source引入到联合查询中。 Then, in the WHERE clause, we can refer to it to decide which set of restrictions we need to apply. 然后,在WHERE子句中,我们可以引用它来决定需要应用哪些限制。

Whether the above query even makes any sense depends on a few things, most important that given_rating and saved_by belong together in a single column report. 上面的查询是否有意义还取决于几件事,最重要的是, given_ratingsaved_by一起属于一个列报告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM