对2列进行查询,就像它们是一个一样

时间:2011-05-25 20:25:56

标签: mysql sql database

有两列包含相同类型的数据:

col_a  col_b ...
Bob    Tim   ..
John   Frank .
Bob    John
John   Tim
Bob    Bob
Frank  John

现在我要做的查询是这样的(计算事件:(Bob,3),(John,2),..):

SELECT col_a, count(*) AS total FROM table1 GROUP BY col_a

但是我没有在col_a上运行它,而是想同时在col_a和col_b上运行它((Bob,4),(John,4),..)

感谢任何帮助

编辑:     谢谢你们每个人都很棒。

再次感谢

3 个答案:

答案 0 :(得分:5)

Select Z.name, Count(*) As Total
From    (
        Select col_a As name
        From total
        Union All
        Select col_b
        From total
        ) As Z
Group By Z.name

答案 1 :(得分:4)

select Name, count(*) as Total
from (
    select col_a as Name from MyTable
    union all
    select col_b from MyTable
) a
group by Name

答案 2 :(得分:1)

根据您的Bob Bob列,我认为您需要对子查询进行分组:

select idx, sum(count)
from (
    select col_a as idx, count(*) as count
    from table
    union all
    select col_b as idx, count(*) as count
    where col_a <> col_b -- avoid dups
    ) as counts
group by idx

或:

select idx, count(*)
from (
    select col_a as idx
    from table
    union all
    select col_b as idx
    where col_a <> col_b -- avoid dups
    ) as counts
group by idx