duancoubeng5909 2011-06-28 14:31
浏览 79
已采纳

MySQL:使用union检查两列是否包含其他值?

I have a friend table with two primary columns (uid and fid) and am essentially trying to see if for example if the friend is also friends of the user, so

uid 5 -> fid 6
uid 6 -> fid 5

I had tried to mix and mash SELECT queries to somehow return a deciding result, however cannot seem to find anything. count() will return either one or two columns (two being correct), however PHP's PDO has no good means to find number of selected (not affected) rows without hackish loops.

(SELECT count(uid) FROM friends WHERE uid = 1 AND fid = 2)
  UNION ALL -- Or plain union
(SELECT count(uid) FROM friends WHERE uid = 2 AND fid = 1)

This of course still returns one or two rows of 0/1 or 0 or 1

Can you think of a way to return either 1 or 0 in MySQL in the first column? or a better way of writing this functionality in to my program? (I try best to avoid hackish things)

  • 写回答

3条回答 默认 最新

  • doufocheng6233 2011-06-28 14:42
    关注
    SELECT a.uid, a.fid
    FROM friends a
      JOIN friends b
         ON a.fid = b.uid
        AND a.uid = b.fid
    WHERE a.uid = 1
      AND a.fid = 2
    

    To avoid "duplicate" rows.. e.g. 2 rows for every couple of friends, add the condition a.uid < b.uid:

    SELECT a.uid, a.fid
    FROM friends a
      JOIN friends b
         ON a.fid = b.uid
        AND a.uid = b.fid
        AND a.uid < b.uid
    WHERE a.uid = 1
      AND a.fid = 2
    

    So, to count all friendships, use:

    SELECT COUNT(*) AS countAllFrienships
    FROM friends a
      JOIN friends b
         ON a.fid = b.uid
        AND a.uid = b.fid
        AND a.uid < b.uid
    

    So, to count friends of user X, use:

    SELECT a.uid
         , COUNT(*) AS numberOfFriends
    FROM friends a
      JOIN friends b
         ON a.fid = b.uid
        AND a.uid = b.fid
    WHERE a.uid = X
    GROUP BY a.uid
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 被蓝屏搞吐了,有偿求帮解答,Ai回复直接拉黑
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角