根据两个表之间的匹配设置列状态

时间:2019-05-03 21:53:45

标签: sql-server

我有两个桌子

T1

for (int i = 0; i < c; i++) {
items.add(options[i]);                            
spinnerDialog=new SpinnerDialog(NewActivity.this,items,"Search","Close");// With No Animation
spinnerDialog=new SpinnerDialog(NewActivity.this,items,"Search",R.style.DialogAnimations_SmileWindow,"Close");// With   Animation

spinnerDialog.setCancellable(true); // for cancellable
spinnerDialog.setShowKeyboard(false);// for open keyboard by default
spinnerDialog.bindOnSpinerListener(new OnSpinerItemClick() {
    @Override
    public void onClick(String item, int position) {
        Intent intent = new Intent(NewActivity.this,PrescriptionActivity.class);
        intent.putExtra("doctor",String.valueOf(items.get(i)));
        NewActivity.this.startActivity(intent);

    }
});
findViewById(R.id.show).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        spinnerDialog.showSpinerDialog();
    }
});

T2

id
1
2
3
4

如果我发现两个表中的ID均匹配,则状态应更新为“是”,否则为“否”

2 个答案:

答案 0 :(得分:0)

一种方法是将CASE表达式和EXITS与相关的子查询一起使用,该子查询检查另一张表中是否存在行。

UPDATE t2
       SET status = CASE
                      WHEN EXISTS (SELECT *
                                          FROM t1
                                          WHERE t1.id = t2.id) THEN
                        'Yes'
                      ELSE
                        'No'
                    END;

答案 1 :(得分:0)

您可以使用LEFT JOIN进行更新。如果t1.id为空,则没有匹配项,您可以将其设置为No。否则,将其设置为是。

UPDATE t2
  SET t2.Status = CASE WHEN t1.id IS NOT NULL THEN 'Yes' 
                       ELSE 'No' 
                  END
  FROM t2
  LEFT JOIN t1
    ON t1.id = t2.id

或者,您可以在CASE

中使用子查询
UPDATE t2
  SET t2.Status = CASE WHEN t2.id IN (SELECT id FROM t1) THEN 'Yes' 
                       ELSE 'No' 
                  END