简体   繁体   中英

mysql query for joining two tables

Table 1

person_id| location_id | field a | field b |friend_id

Table 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 )

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.

First, ensure you have an index on the Friend_ID column so it can be optimized in the query

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. (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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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