Mysql:如何只在SELECT(接受)= 1的位置进行SELECT?

时间:2015-04-15 07:55:02

标签: mysql sql

这是我的代码,它正确显示,除非我想将其限制为仅过滤'已接受'来自朋友表是=' 1' ...截至目前它显示所有

SELECT users.id, users.username, users.avatar, COUNT(friends.accepted) AS friends 
FROM users
  LEFT JOIN friends ON friends.user1=users.username || friends.user2=users.username
GROUP BY users.username
ORDER BY friends DESC LIMIT 20

3 个答案:

答案 0 :(得分:3)

如果您只希望获得一位被接受的朋友,请使用HAVING(为了简单起见,HAVING相当于WHERE,用于过滤汇总结果):

SELECT users.id, users.username, users.avatar, COUNT(*) AS friends 
FROM users
LEFT JOIN friends ON friends.user1=users.username || friends.user2=users.username
GROUP BY users.username
HAVING COUNT(friends.accepted) = 1
ORDER BY friends DESC LIMIT 20

如果你想计算接受的朋友= 1,一个简单的WHERE应该有效:

SELECT users.id, users.username, users.avatar, COUNT(*) AS friends 
FROM users
LEFT JOIN friends ON friends.user1=users.username || friends.user2=users.username
WHERE friends.accepted = 1
GROUP BY users.username
ORDER BY friends DESC LIMIT 20

或者,如果您还想列出没有朋友的人接受= 1:

SELECT users.id, users.username, users.avatar, 
    SUM(CASE friends.accepted = 1 THEN 1 ELSE 0 END) AS friends 
FROM users
LEFT JOIN friends ON friends.user1=users.username || friends.user2=users.username
GROUP BY users.username
ORDER BY friends DESC LIMIT 20

答案 1 :(得分:1)

使用having子句来检查接受的数量是否为1的条件

SELECT users.id, users.username, users.avatar, COUNT(friends.accepted) AS friends 
  FROM users
  LEFT JOIN friends ON friends.user1=users.username || friends.user2=users.username
  GROUP BY users.username
having count(friends.accepted)=1
  ORDER BY friends DESC LIMIT 20

答案 2 :(得分:0)

COUNT(columnname)计算columnname不为null的所有记录。因此,您不想使用COUNT(friends.accepted),因为0和1都不为空,因此您可以计算所有朋友是否被接受。

使用SUM来计算所有接受的= 1。但是,如果用户根本没有朋友,则会获得NULL。在这种情况下使用COALESCE可以将NULL设为零,如果这困扰你的话。

SELECT 
  users.id, 
  users.username, 
  users.avatar, 
  COALESCE(SUM(friends.accepted),0) AS friends 
FROM users
LEFT JOIN friends ON users.username IN (friends.user1, friends.user2)
GROUP BY users.id
ORDER BY friends DESC LIMIT 20;

(在您只是 对接受的朋友感兴趣的简单查询中,您当然可以简单地将AND accepted = 1添加到您的ON子句中,以便只接受被接受的朋友并计算他们与COUNT。)

另一种方法是计算子查询:

SELECT id, username, avatar, 
  (
    select count(*) 
    from friends 
    where users.username in (friends.user1, friends.user2)
    and friends.accepted = 1
  ) as friends
FROM users
ORDER BY friends DESC LIMIT 20;