用于连接两个表的mysql查询

时间:2011-12-26 14:06:51

标签: mysql database

表1

person_id| location_id | field a | field b |friend_id

表2

location_id | location_name

friend_id是给定人喜欢的人的ID(它是可选字段,默认值为零)

如何查询两个表以获取以下内容:

最大人物喜欢的人的location_name等等。

3 个答案:

答案 0 :(得分:1)

首先,确保您在Friend_ID列上有索引,以便在查询中优化它

select
      P.Person_ID,
      P.FieldA,
      P.FieldB,
      L.Location_Name,
      ByPopularity.Popular
   from
      ( select T1.friend_id, count(*) as Popular
           from Table1 T1
           group by T1.friend_id
           order by Popular DESC ) ByPopularity

         JOIN Table1 P
            on ByPopularity.Friend_ID = P.person_ID

            Join Table2 L
               on P.Location_ID = L.Location_ID

编辑 - 关于如何根据人物来源获得最受欢迎的位置的评论

select
      L.Location_Name,
      ByPopularity.PopularLocation
   from
      ( select T1.Location_ID, count(*) as PopularLocation
           from Table1 T1
           group by T1.Location_ID
           order by PopularLocation DESC ) ByPopularity

           Join Table2 L
               on ByPopularity.Location_ID = L.Location_ID

答案 1 :(得分:0)

这将按位置降序返回最受欢迎的个人的friend_ID。 (列出每个朋友不仅仅是“最受欢迎的”你想要的只是“最受欢迎的位置?”(你想要的样本输出总是帮助我们弄清楚你的意思。

Select count(Friend_ID), Friend_ID, Location_Name
from table1
LEFT join table2 on table1.Location_ID = Table2.Location_ID
Group by friend_ID, Location_Name
Order by count(friend_ID) DESC

根据要求的读取方式,这也可能是您的要求:

Select count(T1.Friend_ID), T1.Friend_ID, T3.Location_name
FROM Table1 T1
INNER JOIN table1  T2
  on T1.Person_ID = T2.Friend_ID
  and t1.friend_ID <> 0
INNER JOIN table2 T3
  ON T2.Location_ID = T3.Location_ID
GROUP BY T1.Friend_ID, T3.Location_name
Order by count(T1.Friend_ID) Desc

答案 2 :(得分:0)

这应该可以解决问题,我想:

select
    p2.person_id,
    p2.location_id,
    l.location_name
from
    table1 p2
    join (select friend_id, count(1)
          from table1
          where friend_id > 0
          group by friend_id
          order by count(1) desc) p1 on p1.friend_id = p2.person_id
    join table2 l on p2.location_id = l.location_id