SQL多表查询求助。

来源:百度知道 编辑:UC知道 时间:2024/06/06 08:11:17
比如2个表,A和B
A表和B表都有相同的stu_id字段且主键
查询出 A表里面的年龄都是25的 并且(and) B表里面的姓名都是“王”的。应该怎么写?
select * from A where Age=25 and (select [name] form B where [name]='王')
在我这个错误的基础上改吧。我不想要直接查询多表的,比如:from A,B这种的,也是被迫不能使。

如你所说,这两个表有两个相同的主键,且你要从这两个表里查询出一部分满足条件的数据,首先数据来自这两个表,就要将这两个表关联起来,按你的写法根本不能将两表关联起来,如何将数据查出?你可以这样尝试一下
select * from a where a.age=25 and a.stu_id in (select b.stu_id from b where b.name='王')
且这样只能查询出A表数据,B表数据只作为条件出现了

select * from A where Age=25 and stu_id in(select stu_id from b where
name='王'

select * from a where a.age=25 and a.stu_id in (select b.stu_id from b where b.name='王')