表1:
  姓名   年龄
  张三   20
  李里   23
  王五   13
  马六   18
  .....表2:
  姓名   配偶
 张三   李四
 李四   张三
 王五  (空)
(空)  马六
 .....现在要做以下操作,如果表2中:
 姓名   配偶
 张三   李四
 李四   张三
是这样的一个结构,就是姓名和配偶都对应有名字,就到表1中去查询出张三和李四的年龄总和我用的语句是:
select a.姓名,a.配偶, b.年龄+c.年龄 as 年龄总和 from 表2 a
left join 表1 b on a.姓名=b.姓名
left join 表1 c on a.配偶=c.姓名
where 姓名 is not null and 配偶 is not null
但是查出来的结果为:
姓名  配偶  年龄总和  
张三  李四  43
李四  张三  43有重复了,上面的那个SQL 语句 怎么写,输出才不会有重复,请 高手指点!在线等,谢谢了!~~

解决方案 »

  1.   

    select a.姓名,a.配偶, (select b.年龄 from b where b.姓名=a.姓名) + (select b.年龄 from b where b.姓名=a.配偶) as 年龄总和
    where 姓名 is not null and 配偶 is not null
      

  2.   

    splendor_hh (帅帅)有看到你啊 ,哈哈哈哈
    楼上这种写法的思路真好,简洁!
      

  3.   

    select a.姓名,a.配偶, (select b.年龄 from b where b.姓名=a.姓名) + (select b.年龄 from b where b.姓名=a.配偶) as 年龄总和
    where 姓名 is not null and 配偶 is not null
    一楼的这个就可以!~