在每个插入的mysql递增中插入语句

时间:2014-05-07 09:00:17

标签: mysql sql database

下面是我的mysql表..

create table customer(
    CustId int not null AUTO_INCREMENT primary key,
    FirstName varchar(100) default null,
    LastName varchar(100) default null,
    Gender varchar(40) default null,
    Category varchar(40) default null,
    DateOfBirth date default null,
    Age int(3)default null,
    LastUsed TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 
);

create table address(
    Address_Id int not null AUTO_INCREMENT primary key,
    Address varchar(1000) default null,
    Country varchar(40) default null,
    State varchar (50) default null,
    city varchar(50)default null,
    PinCode varchar(20)default null,
    EmailId varchar(50)default null,
    ContactNo varchar(20) default null,
    MobileNo varchar(20) default null,
    CustId int default null,
    foreign key(CustId) references customer(CustId),
    LastUsed TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 
);


create table username(
    User_Id int not null AUTO_INCREMENT primary key,
    UserName varchar(50)default null,
    CustId int default null,
    foreign key(CustId)references customer(CustId),
    LastUsed TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 
);

create table affiliate(
    Affiliate_Id int not null AUTO_INCREMENT primary key,
    Address_Id int default null,
    foreign key(Address_Id) references address(Address_Id),
    LastUsed TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 
);

create table userlogin(
    Login_Id int not null AUTO_INCREMENT primary key,
    UserName varchar(50) default null,
    PassWord varchar(50)default null,
    Category varchar(40)default null,
    LastUsed TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 
);

我试图运行以下查询:

start transaction;
    insert into userlogin (UserName) select UserName from username where CustId=1;
    insert into userlogin (PassWord)value ('constant');
    insert into userlogin (Category) select Category from customer where CustId=1;
commit;

但是对于每个插件,它会增加如何将所有插入放在一行... 请指导我,因为我试图将数据库知识作为入门者。

提前致谢..

2 个答案:

答案 0 :(得分:1)

我不认为,使用单独的插入查询有任何理由:

INSERT
INTO userlogin
  (
    UserName,
    PassWord,
    Category
  )
  VALUES
  (
    (SELECT UserName FROM username WHERE CustId=1
    ),
    'constant',
    (SELECT Category FROM customer WHERE CustId=1
    )
  )

答案 1 :(得分:0)

你试试这个吗?

start transaction;
insert into userlogin (UserName, PassWord, Category) values ((select UserName from username where CustId=1), 'constant', (select Category from customer where CustId=1))
commit;