关于2表关联的SQL 语句!
表A:
ID father_name
1 张三
2 李四
3 王五
.............
表B:
ID child_name age
1 w 13
1 t 20
2 s 18
3 q 31
.................
现在要关联2表查询 满足以下条件的记录:
只有一个child 的 且年龄 大于 30岁的 记录。
显示记录应该是:
ID father_name child_name age
3 王五 q 31
SQL 应该怎么写呢?(尽量找简洁点的方法)
------解决方案--------------------select * from A
inner join
(
select max(ID) as ID, child_name from B
where age> 30
group by child_name
having count(*)=1
)B on A.ID=B.ID
------解决方案--------------------select a.id,farther_name,child_name,age from A,(select id from B where age> 30 group by id having count(id)=1) B where A.id=b.ID;
------解决方案--------------------select A.id,A.father_name,B.child_name,B.age from A inner join B
on A.id = B.id
where B.age > 30 and (select count(*) from B where B.id = A.id) = 1