doubiao9775 2011-09-01 21:44
浏览 105
已采纳

MySQL计算a = b和b = a的行

This is the first time I've asked a question. It's the first time I've not been able to find what I'm looking for on SO and I think I'm going mad because it should be simple!

Suppose you have a MySQL table, 'T' with two columns 'A', 'B'.

A B
---
1 2
2 1
1 3
3 1
2 4

I'd like to count mutual relations given a variable. So if I supply

X = 1

It should return

2

Because 1, 2 AND 2, 1 exist, and 1, 3 AND 3, 1 exist. However, supply

X = 2

It should return

1

Because 1, 2 AND 2, 1 exists, but no other rows where 2 = n AND n = 2.

I hope this is clear! And apologies if it's simple, feel like I'm on a brain freeze.. Cheers!

  • 写回答

1条回答 默认 最新

  • dqp10099 2011-09-01 22:00
    关注

    This will work (but if you have a row with (n,n) it will also count as a mutual relation):

    select count(*) from T t1
    join T t2 on t1.B = t2.A
    where t1.A = ? and t2.B = ?
    

    (pass the same value in for both parameters)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染