简体   繁体   English

如何根据where子句从两个表中进行选择

[英]How to select from two tables based on a where clause

I am trying to select from two tables and join them where they have the same id but my query seems wrong that it searches for so long that it crashed workbench. 我试图从两个表中选择并加入它们具有相同ID的位置但我的查询似乎错误,它搜索了很长时间以至于它崩溃了工作台。

   SELECT s.id,
          s.title,
          s.votes,
          t.*
     FROM movies_two.movie s, 
          movies_one.movie t 
LEFT JOIN movies_two.movie 
       ON movies_one.id = s.id -- not sure which join to use
    WHERE s.votes = -1 AND
          t.numofvotes > 0;

I have two databases containing similar data. 我有两个包含类似数据的数据库。 I am trying to select rows that from movies_one and movies_two that have the same id and where movies_one has votes = -1 and movies_two has movies > 0 我试图从movies_onemovies_two中选择具有相同ID的行,其中movies_onevotes = -1movies_twomovies > 0

You don't need a left join for this. 您不需要left join Nor do you need a cross join (which is what the comma does in the from clause. 你也不需要cross join (这是逗号在from子句中的作用。

I think you want something like this: 我想你想要这样的东西:

SELECT *
FROM movies_one.movie m1 JOIN
     movies_two.movie m2
     ON m1.id = m2.id AND
        m1.votes = -1 AND 
        m2.numofvotes > 0;

I would also suggest that you use table aliases that are abbreviations for the table names. 我还建议您使用表别名缩写的表别名。 Your text description of what you wand and your query are quite different. 您对魔杖和查询的文字描述完全不同。

SELECT  s.id ,s.title, s.votes, t.*  
FROM movies_two.movie s 
JOIN movies_one.movie t
ON t.id = s.id  
WHERE s.votes =-1  
AND t.numofvotes >0;

Would be okay. 没关系。 You use a left join, when you only want the data in movies_two.movie - the left table. 当您只想要movies_two.movi​​e中的数据时,您可以使用左连接 - 左表。 But here you want the data of both tables. 但在这里你需要两个表的数据。

Try this: 尝试这个:

SELECT * 
  FROM movies_one.movie 
 WHERE numofvotes = -1
 UNION
SELECT * 
  FROM movies_two.movie 
 WHERE votes > 0

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

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