计算MySQL中的对

时间:2014-12-11 16:49:39

标签: mysql

我需要找出一个值存在多少对。

我的表格中包含3个列,如

+----+----------+------+-----------------+
| id | one      | two  | three           |
+----+----------+------+-----------------+
|  1 | steve    | bob  | michael         |
|  2 | bob      | steve| chris           |
|  3 | chris    | sam  | NULL            |
|  4 | michael  | chris| lea             |
|  5 | steve    | lea  | NULL            |
|  6 | susan    | chris| steve           |
|  7 | lea      | steve| bob             |

现在我想找到史蒂夫的对子,包括他们的计数... col 3是“可选的”(可以包含null),“one”和“two”总是被填充。

结果应如下:Steve& Lea 2,Steve&鲍勃2,史蒂夫&克里斯3,史蒂夫&迈克尔1,史蒂夫&苏珊1 ...

编辑:一个更好的例子(数据方式)将是:

+----+--------+--------+--------+--------+
| id | url    | color1 | color2 | color3 |
+----+--------+--------+--------+--------+
|  1 | foo.com| red    | grey   |        |
|  2 | a.com  | white  | red    | grey   |
|  3 | b.com  | black  | white  |        | 
|  4 | z.com  | white  | red    |        |
|  5 | 123.com| white  | grey   | black  |

color1,2,3是网站使用的最突出的颜色(至少2,可选3)。 结果应该是颜色的最常见组合的列表。希望这个例子更有意义。

2 个答案:

答案 0 :(得分:1)

不确定,如果我理解你的问题,但给出了这个样本数据:

CREATE TABLE t
    (`id` int, `one` varchar(7), `two` varchar(5), `three` varchar(7))
;

INSERT INTO t
    (`id`, `one`, `two`, `three`)
VALUES
    (1, 'steve', 'bob', 'michael'),
    (2, 'bob', 'steve', 'chris'),
    (3, 'chris', 'sam', NULL),
    (4, 'michael', 'chris', 'lea'),
    (5, 'steve', 'lea', NULL),
    (6, 'susan', 'chris', 'steve'),
    (7, 'lea', 'steve', 'bob')
;

我接受了这个查询

select
least(a, b) as p1, greatest(a, b) as p2, count(*)
from (
select
one as a, two as b
from
t
where 'steve' in (one, two)
union all
select
one, three
from
t
where 'steve' in (one, three)
union all
select
two, three
from
t
where 'steve' in (two, three)
) sq
group by p1, p2

这个结果:

|      P1 |     P2 | COUNT(*) |
|---------|--------|----------|
|  (null) | (null) |        1 |
|     bob |  steve |        3 |
|   chris |  steve |        2 |
|     lea |  steve |        2 |
| michael |  steve |        1 |
|   steve |  susan |        1 |

这是你正在寻找的吗?

答案 1 :(得分:-1)

SELECT
    CONCAT(one, " & ", two), count(*)
FROM
    myTable
GROUP BY
    1