我有两张桌子:
cities(city_id|Serial, city_name|Text, state_id|Integer)
states(state_id|Serial, state_name|Text)
我想在cities
中插入一行city_name
作为“PortBlair”,并在state_id
states
中插入state_name="Andaman"
。
我的查询:
INSERT INTO cities (city_name,state_id)
VALUES ('PortBlair',select state_id from states where state_name='Andaman')
MySQL中的错误:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select state_id from states where state_name='Andaman')' at line 1
问题1 :这句话有什么问题?我错过了一些qoutes / backquotes /撇号吗?
问题2 :如果插入语句的顺序相同,它是否总是依赖于Serial
数据类型,它总是生成相同的Id?我的意思是,我应该把state_id
自己写成:
INSERT INTO cities (city_name,state_id) VALUES ('PortBlair',1)
答案 0 :(得分:1)
你需要用括号括起select语句作为你的值,
INSERT INTO cities (city_name,state_id)
VALUES ('PortBlair', (select state_id from states where state_name='Andaman'))
但最好使用INSERT INTO...SELECT
声明
INSERT INTO cities (city_name,state_id)
SELECT 'PortBlair' as city_name, state_id
FROM states
WHERE state_name = 'Andaman'
答案 1 :(得分:0)
Q1:
INSERT INTO cities (city_name,state_id)
select 'PortBlair' as city, state_id
from states where state_name='Andaman'
Q2:
是的,你可以自己编写state_id:
INSERT INTO cities (city_name,state_id) VALUES ('PortBlair',1)