有条件地选择行并有条件地插入另一个表

时间:2016-12-01 07:17:01

标签: tsql

如何向表2中插入表A中一行的所有字段值,其中表1中列A中的所有值满足表1的列B的条件,但在表2中不存在。如何使用not exists构建查询?

我试过了:

INSERT INTO Teachermast (
  teacher_code,
  teacher_name,
  designation,
  dept_code,
  contact_no,
  email,
  address,
  dob,
  PASSWORD
) 
SELECT 
  userId,
  username,
  designation,
  dept,
  contact_no,
  email,
  address,
  dob,
  PASSWORD 
FROM
  UserMast 
WHERE NOT EXISTS 
  (SELECT 
    userId 
  FROM
    UserMast 
  WHERE usertype = '3')

但这似乎不起作用。 请帮助。

2 个答案:

答案 0 :(得分:1)

你可以做一个合并

create table users
(
    userId varchar(50),
    username varchar(50),
    usertype int,
    password varchar(50),
    contact_no varchar(50),
    email varchar(50),
    faxno varchar(50),
    address varchar(50),
    created_date date,
    updated_date date,
    status varchar(50),
    gender varchar(50),
    dob date,
    lasttimelogin datetime,
    login_time datetime,
    logoutt_time datetime,
    designation varchar(50),
    dept varchar(50),
    email_pass varchar(50)
)
insert into users values('T0003','Ankita',3,'12345','9858‌​585245','anki@gmail.com','201','l block noid sec 25',NULL,NULL,NULL,'Female','11/09/1990',NULL,NULL,NULL,'Teacher','EC',NULL); 
insert into users values('T0004','Ribha',3,'12345','9512365423','sharma@gmail.com',NULL,'221 dwarka sec 10',NULL,NULL,NULL,'Female','12/02/1989',NULL,NULL,NULL,'Teacher','EC',NULL);

create table teachers
(
    teacher_code varchar(50),
    teacher_name varchar(50),
    designation varchar(50),
    dept_code varchar(50),
    contact_no varchar(50),
    email varchar(50),
    address varchar(50),
    dob date,
    password varchar(50)
) 
insert into teachers values('T0002','Tanvi','Teacher','CS','9632569856','tan123@gmai‌​l.com','298 mayur vihar ph 1','29/06/1990','12345');
insert into teachers values('T0003','Ankita','Teacher','EC','9858585245','anki@gmail‌​.com','201 l block noida sec 25','11/09/1990','12345');

merge teachers as target
using (select userid, username, designation, dept, contact_no, email, address, dob, password from users where usertype = 3) 
as source(userid, username, designation, dept, contact_no, email, address, dob, password)
    on target.teacher_code = source.userid
when not matched by target then
    insert (teacher_code, teacher_name, designation, dept_code, contact_no, email, address, dob, password)
    values (source.userid, source.username, source.designation, source.dept, source.contact_no, source.email, source.address, source.dob, source.password);

select * from teachers

但是,我认为您的数据库设计存在问题。使用当前的模型,例如,与table2相比,table1中的Ankita可能有不同的地址(或密码!)。如果您更改了任何信息,则必须在两个地方进行更改。

例如,您是否可以将所有人插入“用户”并让“老师”成为视图

select {columns} from users where usertype = 3

答案 1 :(得分:0)

请尝试此查询

SELECT 
    t.userId,
    t.username,
    t.designation,
    t.dept,
    t.contact_no,
    t.email,
    t.address,
    t.dob,
    t.PASSWORD 
FROM Teachermast as  t
LEFT join UserMast as u on t.userId = u.teacher_code
WHERE t.usertype = '3' and u.teacher_code is null