如何在table1中插入行,其中table1的col1和col2与table2的col1和col2不匹配

时间:2016-10-16 15:14:41

标签: sql-server join

我有table1这样的:

date       ticker   po       tag1
2016-10-13    UX1 -206.0000  SV
2016-10-13    UX2 -617.0000  SV
2016-10-13     EP -647.0000  SV
2016-10-14    UX1 -206.0000  SV
2016-10-14    UX2 -617.0000  SV
2016-10-14     EP -647.0000  SV

table2

date       ticker   po       tag1
2016-10-14    UX1 -206.0000  SV
2016-10-14    UX2 -617.0000  SV
2016-10-14     EP -647.0000  SV
2016-10-15    UX1 -206.0000  SV
2016-10-15    UX2 -617.0000  SV
2016-10-15     EP -647.0000  SV

我想在table1的{​​{1}}中插入新闻行,其中table2tickerdate的组合不匹配tag1 1}}组合 有这样的:

table1

我是SQL服务器的新手,这看起来非常简单,但我无法使其发挥作用。

谢谢

2 个答案:

答案 0 :(得分:1)

使用NOT EXISTS

INSERT INTO table1
            (date,ticker,po,tag1)
SELECT date, ticker, po, tag1
FROM   table2 t2
WHERE  NOT EXISTS (SELECT 1
                   FROM   table1 t1
                   WHERE  t1.ticker = t2.ticker
                          AND t1.date = t2.date
                          AND t1.tag1 = t2.tag1) 

当找到匹配的记录时,sub-query会返回1,NOT EXISTS会删除这些记录

答案 1 :(得分:1)

您也可以使用加入

typedef struct{
  int x,y;
  bool isWall;
  material type;
}field;

#define n 16
#define m 12
int x=5;
int y=5;


void display( field **playground ){

  for (int j = 0; j < m; j++)
  {
    for (int i = 0; i < n; i++)
    {
       if (playground[i][j].isWall )
       {
          cout << "*";
       }
       else

          if (x == i && y == j){
             cout << "O";
          }
          else {
             cout << " ";
          }
    }
    cout << endl;
  }

}

int main(){


  field playground[n][m];
  for (int i=0; i<n; i++){
    for (int j=0; j<m; j++){
      playground[i][j].x=i;
      playground[i][j].y=j;
      playground[i][j].isWall=(i==0||i==(n-1)||(j==0&&i!=3) ||j==(m-1));
      if (playground[i][j].isWall && !(i==3 && j==0))
        playground [i][j].type=stone;
      else
        playground [i][j].type=wood;
    }
  }
  display(playground);

}