1

我有 2 张桌子:

cities(city_id|Serial, city_name|Text, state_id|Integer)
states(state_id|Serial, state_name|Text)

我想在“PortBlair”中插入一行citiescity_namestate_idstateswhere中获取对应的行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:这个说法有什么问题?我错过了一些引号/反引号/撇号吗?

问题2:如果插入语句的顺序相同,我是否应该依赖Serial数据类型,它总是会生成相同的 Id?我的意思是,我应该把state_id自己写成:

INSERT INTO cities (city_name,state_id) VALUES ('PortBlair',1)
4

2 回答 2

1

您需要用括号括起来选择语句,因为您正在获得价值,

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'
于 2012-10-21T17:24:31.933 回答
0

Q1:

INSERT INTO cities (city_name,state_id) 
select 'PortBlair' as city, state_id 
from states where state_name='Andaman'

Q2:

Yes, you can write state_id your self:

INSERT INTO cities (city_name,state_id) VALUES ('PortBlair',1)
于 2012-10-21T17:24:54.017 回答