简体   繁体   中英

PHP/SQL: Using only one query, SELECT rows from two tables if data is in both tables, or just SELECT from one table if not

I have two rating/votes tables. One for user votes and stats and another for external votes. The external votes table always have data because it has a DEAFULT = 0, but the users votes only contains data if any user have voted for that specific ID.

So I do something like this:

    $sql = 'SELECT  ratings_stats.votes, ratings_stats.total_value,
                   ratings_stats.view, ratings_stats.fav, ratings_stats.wish,
                   ratings_external.votes, ratings_external.total_value
            FROM ratings_stats, ratings_external
            WHERE ratings_stats.imdbID = ?
            AND ratings_stats.imdbID = ratings_external.imdbID
            LIMIT 1';

I want to select data from both tables if available OR only form the second (external votes) table if not.

How to can I do it without making a new query?

SELECT  ratings_stats.votes, 
        ratings_stats.total_value,
        ratings_stats.view, 
        ratings_stats.fav, 
        ratings_stats.wish,
        ratings_external.votes, 
        ratings_external.total_value
FROM  ratings_external
LEFT JOIN ratings_stats ON ratings_stats.imdbID = ratings_external.imdbID
WHERE ratings_external.imdbID = ?
LIMIT 1

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