select
(
select
name
from
B b
where
a.id=b.id
) name
from
A a;
为什么不能写作:
select
(
select
name
from
b
where
a.id=b.id
) name
from
A a,B b;
表的别名不能接在from后面。
你第一个sql实际上把B表查了两次。
另外不确定你最后是不是省略了A表和B表的关联条件,这个不关联会导致数据行数翻倍。常见的写法应该长这样
select
(select name from B b
where a.id=b.id) name
from A a
或者
select b.name name
from A a left join B b
on a.id=b.id
如果数据都能匹配上的话,还可以这么写
select b.name name
from A a , B b
where a.id=b.id
如果要多次使用某个表,可以使用with,例如
with b as (select * from B)
select
(select name from b
where a.id=b.id) name
from A a,b;
select b.name from A a,B b where a.id=b.id
可以这样写
1.题主书写格式有误,子查询里没有from B表,执行不了;且这种书写格式有很大问题,子查询请放在from后面,对将来的学习工作都有用很多,select后不要加子查询;
2.
写法一:
select B.name from A,B where A. id=B. id
写法二:
select b.name from A a join B b on a. id= b.id
3.上面写法推荐能用第二种就用第二种,同时因为你题目的问题,这个sql没有实际意义,AB两表通过id相连,然后取B表的名字字段,没有其余筛选条件,得出的结果跟
select name from B 没有区别。