doulan8330 2016-11-18 14:38
浏览 27
已采纳

在sql查询中检查两个单独的东西

I am trying to create a friend relationship query. I want the following query to do two things, rather than making another very similar query.

I am wanting to check for pending requests and sent requests. Pending requests are when the user is friend_two. Sent requests are when friend_one is the user_id.

So, is there anyway I can adjust my where clause to something like this (I do not know how to write this out in SQL) -

WHERE friend_one = ? As pending_user
WHERE friend_two = ? AS sent_user

I am not sure if AScan be added to a where clause. The thing about the code I just wrote above is that the placeholder value will be the same value and I am not sure how I could write that in the php.

Right now, if I have the same user in the friend_one and friend_two column it counts all of the occurences of the user's occurence ie: if user #2 has his id in the friend_one column only 2 times, but has his id comes up in the friend_two column 8 times, the query will count 10 because of m,y where clause. I need the values to be 2 and 8.

How can I do this? See code and table below.

SELECT *, COUNT(friend_one) AS pending_count , COUNT(friend_two) AS requests_sent   
FROM friends
WHERE friend_one OR friend_two = ?
AND status = ?

friends table

Table
Create Table
friends
CREATE TABLE `friends` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `friend_one` int(11) NOT NULL DEFAULT '0',
 `friend_two` int(11) NOT NULL DEFAULT '0',
 `status` enum('0','1','2') COLLATE utf8_unicode_ci DEFAULT '0',
 `date` datetime NOT NULL,
 PRIMARY KEY (`id`),
 KEY `friend_two` (`friend_two`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Square = requests_sent

Circle = pending_count

enter image description here

  • 写回答

1条回答 默认 最新

  • douzhuangna6906 2016-11-18 14:42
    关注

    with @name, @status parameters. I belive you want something like this.

    SELECT COUNT(CASE WHEN `friend_one` = @name THEN 1 END) as `pending_count`,
           COUNT(CASE WHEN `friend_two` = @name THEN 1 END) as `requests_count`
    FROM friends
    WHERE @name IN ( `friend_one` , `friend_two` )
      AND `status` = @status
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?