2015-08-18 21 views
1

我有两个表,我想获取包含相同字段值的相同行。例如:从两个表中返回相同的值

表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服务器版本使用附近的“表选手T2其中t2.id = t1.id和t2.self”在行3

回答

0

,或者你可以用简单的选择

select a.* from table1 a, table2 b where a.id = b.id and a.team=b.self 
+0

为什么在选择列表中包含table2行?如果table2包含重复项,也会返回重复的table1行。 – jarlh

+0

@jarlh当然,这是多余的,改变 –

+0

@Bender,很高兴我帮助了你,并感谢你接受了 –

1

使用EXISTS返回一个table1的正确语法手册如果排表2包含匹配行:

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) 
+0

你的意思是选择t1在哪里? – Bender

+0

您可以在EXISTS子选择中选择任何你想要的。我总是选择1.重要的是如果一行存在或不存在! (您不使用选定的值...) – jarlh

+0

对不起,现在我看到了我的错字...当然,它应该是“从table2中选择1”的子选择。现在纠正! – jarlh

0

做这种下一个你可能会得到你的输出尝试。

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

谢谢。