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 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法