简体   繁体   中英

how to insert values of foreign key constraint from other table?

table name category and table columns

1) cat_id (primary key)
2) cat_title

the other table is book and the columns are

1) book_id (primary key)
2) book_title
3) cat_id(foreign key)

for the foreign key constraint i was trying the following query:

INSERT INTO book VALUES (1,'new book',(SELECT `cat_title` FROM `categroy` WHERE `cat_id`=3))

it is not working. is their anybody to please tell how can i improve this query so that it can come into order. help shell highly be appriciated

I see 2 problems in your query.

First, you always use "1" as your new key. It will create an error if you already have that key in your book table. You could use NULL there.

Second, there is a typo on "FROM categroy". Should be: "FROM category".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM