简体   繁体   English

mysql查询联接两个表

[英]mysql query for joining two tables

Table 1 表格1

person_id| location_id | field a | field b |friend_id

Table 2 表2

location_id | location_name

friend_id is the id of a person liked by the given person ( it's an optional field and the default value is zero ) friend_id是给定人员喜欢的人员的ID(这是一个可选字段,默认值为零)

How can I query the two tables to get the following : 我如何查询两个表以获取以下信息:

the location_name of the person who has been liked by the maximum people and so on in decreasing order. 最多人喜欢的人的location_name,依此类推,以降序排列。

First, ensure you have an index on the Friend_ID column so it can be optimized in the query 首先,确保在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

EDIT -- PER COMMENT on how to get most popular location based on people originations 编辑-关于如何根据人物来源获得最受欢迎的位置的评论

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

This will return the friend_ID of the most popular individuals by location in descending order. 这将按位置降序返回最受欢迎的个人的friend_ID。 (listing each friend not just "the most popular" DO you want just the "most popular by location? (sample output of what you want ALWAYS helps us figure out what you mean. (列出每个朋友不只是“最受欢迎”,您是否只希望按位置列出“最受欢迎”?(总是输出示例信息,这有助于我们弄清您的意思。

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

Depending on how the requirements are read this may also be what your after: 根据需求的理解方式,这可能也是您的追求:

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

This should do the trick, I think: 我认为这应该可以解决问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM