我有三个表:store
,users
和storeuser
。
表storeuser
具有store
和users
表的Foreigns键。
这三个表的id列为storeid
,userid
,suserid
,并且所述id列的自动递增。
现在我想将数据从表storeuser
和表store
插入到表user
中:
CREATE TABLE `store2`.`store` (
`storeid` INT(10) NOT NULL AUTO_INCREMENT,
`sname` CHAR(45) NOT NULL,
`stype` CHAR(45) NOT NULL,
`location` CHAR(45) NULL,
PRIMARY KEY (`storeid`));
CREATE TABLE `store2`.`users` (
`userid` INT(10) NOT NULL AUTO_INCREMENT,
`uname` CHAR(45) NOT NULL,
`age` SMALLINT(5) NOT NULL,
PRIMARY KEY (`userid`));
CREATE TABLE `store2`.`storeuser` (
`suserid` INT(10) NOT NULL,
`storeid` INT(10) NOT NULL,
`userid` INT(10) NOT NULL,
PRIMARY KEY (`suserid`),
INDEX `storeid_idx` (`storeid` ASC),
INDEX `userid_idx` (`userid` ASC),
CONSTRAINT `storeid`
FOREIGN KEY (`storeid`)
REFERENCES `store2`.`store` (`storeid`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `userid`
FOREIGN KEY (`userid`)
REFERENCES `store2`.`users` (`userid`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
答案 0 :(得分:0)
你的要求很奇怪,或者我不能理解它。
所以基本上,你想要为每对storeid&和一对名称提供一个名为suserid(自动增量)的ID。 userid(再次自动增量)彼此没有关系?
我不确定我是否理解你,但根据我的理解,这是一个解决方案:
mysql> select * from store;
+---------+-------+-------+----------+
| storeid | sname | stype | location |
+---------+-------+-------+----------+
| 1 | a | b | c |
| 2 | a1 | b2 | c3 |
+---------+-------+-------+----------+
mysql> select * from users;
+--------+-------+-----+
| userid | uname | age |
+--------+-------+-----+
| 1 | 1 | 2 |
| 2 | 3 | 4 |
+--------+-------+-----+
mysql> desc storeuser;
+---------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+----------------+
| suserid | int(10) | NO | PRI | NULL | auto_increment |
| storeid | int(10) | NO | MUL | NULL | |
| userid | int(10) | NO | MUL | NULL | |
+---------+---------+------+-----+---------+----------------+
现在我将插入到storeuser:
mysql> insert into storeuser select '',storeid, userid from store join
users on store.storeid=users.userid;
INSERT之后:
mysql> select * from storeuser;
+---------+---------+--------+
| suserid | storeid | userid |
+---------+---------+--------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
+---------+---------+--------+
这是你需要的吗?