从两个表中获取数据,只从第二个表中获取一行

时间:2018-02-03 17:24:03

标签: mysql sql database join jointable

我有两张桌子

T1:

moving 7-day slope

T2:

sno  val
12   A
13   B
14   C

使用以下查询:

refid   val2
13      ba
13      bb
13      bc

和查询

select * from t1,t2 where t1.sno=t2.refid order by t2.refid;

我得到了

select * from t1 join t2 on t2.refid = ( select refid from t2 where t1.sno = t2.refid limit 1 )

我想只获得第一个组合,而不是像

那样全部三个
B ba
B bb
B bc
    and so on for all the possible combinations.

我的意思是,我只想在加入时获得每三个组合的第一行。

4 个答案:

答案 0 :(得分:0)

如果您只需要第二个表中的一个值和一个列,则相关子查询是一个简单的解决方案:

select t1.*,
       (select t2.val2
        from t2
        where t1.sno = t2.refid
        order by ?  -- whatever defines "first"
        limit 1
       ) as val2
from t1
order by t1.sno;

如果你只想要匹配的行,MySQL有一个适合账单的having的很好的扩展名:

select t1.*,
       (select t2.val2
        from t2
        where t1.sno = t2.refid
        order by ?-- whatever defines "first"
        limit 1 
       ) as val2
from t1
having val2 is not null
order by t1.sno;

答案 1 :(得分:0)

据我所知,我建议以下两种方法来获得所需的输出:

方式1: 使用嵌套查询按记录分组然后加入

select * from t1 a join (select * from t2 group by refid) b on a.sno= b.refid

way2: 但最好为t2这样的表添加自动增量键。添加自动增量键后,在大多数用例中都会有用。

首先使用以下命令

将自动增量键添加到表t2

ALTER TABLE t2 add column id int(11) key auto_increment first;

然后执行以下连接查询:

select * from t1 a join (select *from t2 where t2.id in(select min(id) from t2 group by refid)) b on a.sno= b.refid

答案 2 :(得分:0)

select t1.val,temp.refid from t1,(select t2.refid as refid, min(t2.val2) as val2 /*Assuming "first" row criteria*/ from t2 group by t2.refid) temp where t1.sno=temp.refid order by t2.sno;

使用子查询消除了t2的重复,并与t1结合。

答案 3 :(得分:-1)

select * from(选择ROW_NUMBER()OVER(PARTITION BY sno ORDER BY val2)AS rn,*来自[dbo]。[t1] a 在[.sno = b.refid]上加入[dbo]。[t2] b )t 其中rn = 1