MySQL - 在任一列中查找对

时间:2013-06-14 17:02:21

标签: php mysql sql json

我有一个非常大的表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
+-------+--------+----------+--------+

基本上我需要能够确定给定用户(name1)点击给定名称(name2)的次数,然后确定相反的次数 - {{1}次多少次点击了name2。当Simpson加载他的页面时,他应该根据包含他的名字的匹配对的组合name1看到按顺序排列的名单。该列表如下所示:

count

当有点击时,我可以将它插入表中没问题,但我不知道如何查询这样的东西...我想它最终需要作为JSON对象/数组出来所以这可以被制作成一个原生的移动应用程序,所以如果你想要这样做也可以获得奖励积分!

2 个答案:

答案 0 :(得分:2)

对于Simpson,您希望包含名称为“Simpson”的行,但您要选择的名称(和计数)是“非Simpson”名称。你可以这样做:

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

答案 1 :(得分:0)

这将从数据库中获得结果:

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将向您展示如何解析结果并将其转换为JSON字符串,随时可以发送到您的应用程序。