mysql传递子查询

时间:2017-09-02 05:34:44

标签: mysql sql join

这个查询(让f)给我id [4,14,21]一个user_id 1的朋友

select  u1.id  from friends as f1 
inner join users u1 on u1.id =  CASE f1.to_user WHEN 1 THEN f1.from_user ELSE f1.to_user END 
where f1.to_user=1 or f1.from_user=1

及以下查询计算两个用户(让用户和他的朋友)之间的共同朋友

select  users.id,users.name, 
(SELECT count(distinct f1.id ) FROM friends as f1 WHERE (f1.to_user = (4,14,21) and f1.from_user = users.id) or (f1.to_user = users.id and f1.from_user in (4,14,21)) ) ) as m from friends 
inner join users on users.id =  CASE friends.to_user WHEN 1 THEN friends.from_user ELSE friends.to_user END 
where friends.to_user=1 or friends.from_user=1

我想将两个查询合并为一个,如下所示

select  users.id,users.name, 
(SELECT count(distinct f1.id ) FROM friends as f1 WHERE (f1.to_user in (f)and f1.from_user = users.id) or (f1.to_user = users.id and f1.from_user in (f) ) ) as m,
(select  u1.id  from friends as f1 inner join users u1 on u1.id = (CASE f1.to_user WHEN 1 THEN f1.from_user ELSE f1.to_user END) where f1.to_user=1 or f1.from_user=1)  as f
from friends inner join users on users.id =  CASE friends.to_user WHEN 1 THEN friends.from_user ELSE friends.to_user END 
where friends.to_user=1 or friends.from_user=1

但错误 子查询返回超过1行 , 任何人都说出解决这个问题的好方法

1 个答案:

答案 0 :(得分:1)

您的计数(不同的f1.id)返回1行,但as status查询返回多行,因此您有错误
如果您只需要as status查询中的一行,则可以在子查询中使用限制1

但如果您需要所有行,则应根据u1.id

加入子查询

例如:

  Select  
         users.id
        , users.name
        , (SELECT count(distinct f1.id ) 
              FROM friends as f1 
              WHERE (f1.to_user in (status)and f1.from_user = users.id) or (f1.to_user = users.id and f1.from_user in (status) ) ) as m
        , t_status.status
  from friends 
  inner join users on users.id =  CASE friends.to_user WHEN 1 THEN friends.from_user ELSE friends.to_user END 
  inner join ( select  u1.id  as status
              from friends as f1 
              inner join users u1 on u1.id = (CASE f1.to_user WHEN 1 THEN f1.from_user ELSE f1.to_user END) 
              where f1.to_user=1 or f1.from_user=1) t_status on t_status.status = users.id
  where friends.to_user=1 or friends.from_user=1

如果您只需要子选择中的行作为状态,则可以使用限制

任意获取一行
Select  
       users.id
      , users.name
      , (SELECT count(distinct f1.id ) 
            FROM friends as f1 
            WHERE (f1.to_user in (status)and f1.from_user = users.id) or (f1.to_user = users.id and f1.from_user in (status) ) ) as m
      , (select  u1.id  
            from friends as f1 
            inner join users u1 on u1.id = (CASE f1.to_user WHEN 1 THEN f1.from_user ELSE f1.to_user END) 
            where f1.to_user=1 or f1.from_user=1  
            order by u1.id limit 1)  as status
from friends 
inner join users on users.id =  CASE friends.to_user WHEN 1 THEN friends.from_user ELSE friends.to_user END