简体   繁体   中英

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_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??

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. Then, in the WHERE clause, we can refer to it to decide which set of restrictions we need to apply.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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