开发者

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

开发者 https://www.devze.com 2023-01-08 20:50 出处:网络
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 d

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
0

精彩评论

暂无评论...
验证码 换一张
取 消