简体   繁体   中英

MySQL - Find pairs in either column

I have a VERY large table called fullNames :

+----+-----------+----------+--------+
| id | name1     | name2    | count  |
+----+-----------+----------+--------+
| 1  | Homer     | Simpson  |   2    | <-- Homer clicked Simpson's name 2 times
| 2  | Bart      | Simpson  |   1    | <-- Bart clicked Simpson's name once
| 3  | Simpson   | Bart     |   4    | <-- Simpson clicked Bart's name 4 times
......................................
......................................
| 80 | Steven    | Baldwin  |   7    | <-- Steven clicked Baldwin's name 7 times
| 81 | Alec      | Baldwin  |   6    | <-- Alec clicked Balwin 6 times, but there's NO relationship w/ Steven's clicks
+-------+--------+----------+--------+

Essentially I need to be able to determine how many times the given user ( name1 ) has clicked on a given name ( name2 ), then determine the opposite - how many times name2 has clicked on name1 . When Simpson loads up his page, he should see a list of names put in order based on the combined count s of matching pairs that include his name. That list would look like this:

Bart       5
Homer      2

When there's a click, I can insert it into the table no problem, BUT I don't know how to query for something like this... I guess it would ultimately need to come out as a JSON object/array so this can be made into a native mobile app, so bonus points if you feel like working that out too!

For Simpson , you want to include rows where either name is "Simpson", but the name you want to select (and count for) is the "non-Simpson" name. You can do it like this:

SELECT
  CASE WHEN Name1 <> 'Simpson' THEN Name1 ELSE Name2 END AS ClickName,
  SUM(count) AS ClickCount
FROM fullNames
WHERE 'Simpson' IN (Name1, Name2)
GROUP BY CASE WHEN Name1 <> 'Simpson' THEN Name1 ELSE Name2 END
ORDER BY ClickCount DESC

This will get you the results from the database:

SELECT name, SUM(`count`)
FROM (
    -- records where "your_input_name" is the clicker
    SELECT name2 AS name, `count`
    FROM fullNames
    WHERE name1 = "your_input_name"

    UNION

    -- records where "your_input_name" is the "clickee"
    SELECT name1 AS name, `count`
    FROM fullNames
    WHERE name2 = "your_input_name"
) AS sub
GROUP BY name
ORDER BY `count` DESC

This other question will show you how to parse the result and convert it as a JSON string, ready to be sent to your application.

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