简体   繁体   English

PHP / SQL:仅使用一个查询,如果两个表中都有数据,则从两个表中选择行;否则,仅从一个表中进行SELECT

[英]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. 外部投票表始终具有数据,因为它的DEAFULT = 0,但是用户投票仅包含任何用户为该特定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

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

相关问题 从2个表PHP的一个SELECT sql查询中检索2行 - Retrieving 2 rows from one SELECT sql query with 2 tables PHP SQL 从两个表中选择数据,一行 -> 多行 - SQL Select data from two tables, one row -> multiple rows mysql join查询从两个表中选择行,一个表有多个与第一个表匹配的行 - mysql join query for select rows from two tables that one table is having multiple rows matching to the first table 使用一个查询/选择语句从两个表中提取数据 - pull data from two tables with one query/ select statement 比较2个表并从一个表中选择数据 - Compare 2 tables and select data from one table 选择SQL查询以从多个表中获取数据并在一个表中查看 - Select SQL query to get data from multiple tables and view in one table 如何通过一个查询在php mysql中选择和获取两个表数据? - How to Select and Fetch two tables Data in php mysql with one query? 如何从两个表中进行选择,并且仅显示一个表中的一项,而第二个表中的多项呢? - How to select from two tables and display only one item from 1 table and many from the second table? 如何在MySQL中选择两个表,但仅从第二个表中选择一列? - How can I select two tables in MySQL but only select one column from the 2nd table? 从两个表中选择,从第二个表中按一行排序 - select from two tables ordering by one row from second table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM