原始问题:原本想为两个多对多关系的派生关系表添加关系,是的两表中某些数据产生关系。结果爆出错误,在此上下文中不允许使用子查询。只允许使用标量表达式。
举例说说,假设有A表和B表,A和B是多对多的关系(各自表内没有相同字段),为A和B增加一个关系表AB表。
AB表分别持有A表和B表的主键作为自己的外键(AB表为无主键表),并且以这两个外键确定一个关系。
第一次使用句子:
insert into tt_user_func (user_id_,func_id_)
values(
select u.user_id_ from t_loginuser u where u.user_code_='602001',
select f.func_id_ from t_function f where f.func_code='7940'
)
爆出错误,在此上下文中不允许使用子查询。只允许使用标量表达式。看到错误以后当场不会了,没见过呀!
上网一搜,原来有些地方不允许子查询,有网友说sqlserver不允许这么写(语法问题),但是依然没有找到解决办法,没办法,自己试。
第二次使用句子:
insert into tt_user_func (user_id_,func_ic_)
values(select u.user_code_,f.func_code_ from t_loginuser u inner join t_function f
on u.user_code_ is not null and f.func_code_ is not null
where u.user_code_='602001' and func_code_='7940')
又出错了,不过这回好点,提示说select 附近有语法错误,写这句的想法是把子查询出来的两个数据对应到values里,结果还是错的,继续试。
第三次使用句子:
insert into tt_user_func (user_id_,func_ic_)
select u.user_code_,f.func_code_ from t_loginuser u inner join t_function f
on u.user_code_ is not null and f.func_code_ is not null
where u.user_code_='602001' and func_code_='7940'OK!成功了!
在附录一些查错误时网友出现的问题及解决方案:
CHECK约束里不能写select子查询,check(name in(select name from XXX where xx=?))这么写是错的,应该这样写check(gender in('male','female'))
另外,还看到有使用变量解决本问题,先定义一个变量,然后用那个子查询查出的值给变量赋值,最后把子查询替代为变量就OK啦!