从两个表中返回相同的值

时间:2015-08-18 07:46:59

标签: php mysql sql

我有两个表,我想获得包含相同字段值的相同行。例如:

表1结构:

ID| CAPTION | TEAM
 0| Example | hi

表2结构:

ID|  TEAM  | SELF
 0|  Eam2  | hi

所以我想在一个查询中返回包含TEAMSELF字段相等的所有行。在这种情况下,我正在等待这个结果:

0 - Example - hi

我怎么能做到这一点? sql中的语句是什么?

可能的解决方案:

select *
from teams t1
where exists (select 1 from table players t2
                where t2.id = t1.id
                and t2.self = t1.players)
  

#1064 - 您的SQL语法出错;查看与MySQL服务器版本对应的手册,以便在'table players t2附近使用正确的语法,其中t2.id = t1.id和t2.self'在第3行

3 个答案:

答案 0 :(得分:1)

如果table2包含匹配的行,则使用EXISTS返回table1行:

select t1.id, t1.caption, t1.team
from table1 t1
where exists (select 1 from table2 t2
              where t2.id = t1.id
                and t2.self = t1.team)

答案 1 :(得分:1)

尝试使用以下内容,您可以获得输出。

select * 
from table1 t1, table2 t2
where t1.id = t2.id  and a.team = b.self;

感谢。

答案 2 :(得分:0)

或者您可以通过简单的选择

来完成
select a.* from table1 a, table2 b where a.id = b.id and a.team=b.self