用于从两个表中获取行的SQL查询

时间:2015-06-24 19:51:39

标签: sql

我有两个带ID和值列的表。

我想联合这两个表,但如果第二个表中存在ID,我想丢弃第一个表中的所有相同ID,并从第二个表中仅检索这些ID。如何为此创建查询?

第一张表:

ID    Value
100   1
100   2
101   3
102   4

第二张表:

ID   Value
100  5
100  6
100  7
102  5

我想要达到的结果:

ID   Value
100  5
100  6
100  7
101  3
102  5

我尝试按照建议进行操作,但它仍然只返回表1中的值:

String selectQuery = "SELECT * FROM " + TABLE1_NAME
                +" UNION ALL"
                +" SELECT * FROM " + TABLE2_NAME
                +" WHERE "+id+" NOT IN (SELECT "+id+" FROM "+TABLE2_NAME+ ")";

3 个答案:

答案 0 :(得分:3)

  select id,value from table1 
  union ALL
  select id , value from table2 
  where id not in (select id from table1)

根据Ormoz的建议进行编辑:

如果两个表都有id,则使用table2的结果:

  select id,value from table2
  union ALL
  select id , value from table1 
  where id not in (select id from table2)

我的测试:

 create table table1 (id int not null, value int not null);

insert into table1 values
 (100,   1),
 (100,   2),
 (101,  3),
 (102,   4);



create table table2 (id int not null, value int not null);

insert into table2 values
(100,  5),
(100,  6),
(100,  7),
(102,  5);


select id,value , 't2' as t from table2
 union ALL
 select id , value, 't1' from table1 
 where id not in (select id from table2);

这是输出:

# id, value, t
'100', '5', 't2'
'100', '6', 't2'
'100', '7', 't2'
'102', '5', 't2'
'101', '3', 't1'

答案 1 :(得分:0)

也许这可以解决问题?

root@******:~# mysql -h******.com -u root -p
ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0

答案 2 :(得分:0)

通过删除首先选择的where子句来解决我的问题:

ts = np.interp( ts_rng.asi8 ,data.index.asi8, data[0] )

特别感谢@ Tim3880和@Ormoz =)