根据特定表

时间:2017-04-19 14:34:57

标签: mysql

enter image description here我有两张桌子:

表t1:

+-----+----+  
| i1  | c1 |  
+-----+----+  
| 11  | abc |  
| 22  | bbc |  
| 33  | cbc |  
+-----+-----+  

表t2:

+-----+----+  
| i2  | c2 |  
+-----+----+  
| 22  | cc |  
| 33  | bb |  
| 33  | bb |  
| 44  | aa |
| 22  | cc |  
+-----+----+  

,输出应为

+----+-----+----+  
| i1 | c1  | c2 |
+----+-----+----+   
| 22 | bbc | cc |
| 33 | cbc | bb |
+----+-----+----+

我尝试加入但无法获得确切的输出

获取table1.user_id,table1affiliate_id,其中table1.affiliate_id = table2.id 应该只从表一给出reslut例如:table1有26行,table2有125行,其中table2有table1的所有26行以及更多,所以我需要输出只打印来自两个表的26个相关字段...

2 个答案:

答案 0 :(得分:0)

此SQL将帮助您:)

SELECT t1.i1, t1.c1, t2.c2
FROM t1, t2
WHERE t1.i1 = t2.i2
GROUP BY t1.i1, t1.c1

答案 1 :(得分:0)

应避免隐式连接

   drop table if exists t1;
    create table t1(i1 int, c1 varchar(3));
    insert into t1 values  
    ( 11  ,'abc'),  
    ( 22  ,'bbc'),  
    ( 33  ,'cbc');  


drop table if exists t2;
create table t2 ( i2 int, c2 varchar(2));  
insert into t2 values
( 22  , 'cc'),  
( 33  , 'bb'),  
( 33  , 'bb'),  
( 44  , 'aa'),
( 22  , 'cc');  


select distinct t1.i1,t1.c1,t2.c2
from t1
join t2 on t2.i2 = t1.i1

+------+------+------+
| i1   | c1   | c2   |
+------+------+------+
|   22 | bbc  | cc   |
|   33 | cbc  | bb   |
+------+------+------+
2 rows in set (0.00 sec)