2016-05-12 2 views
-2

2列X、Yのテーブルがあります。両方の列の各レコードの外観の数を数えたいと思います。 例:Mysql:2つの列のすべての値の数を取得します。

X | Y 

A | A 
B | A 
B | C 
D | C 

結果がどのように私は、MySQLでこれを達成ん

variable | X_count | Y_count 
A  | 1  | 2 
B  | 2  | 0 
C  | 0  | 2 
D  | 1  | 0 

すべきですか?

編集:はい、数時間を費やした後、私はYのすべての値がXのサブセットであることを確認しました。つまり、X_countは決して0になりません。これは最適化に役立ちますか?

答えて

0

私はYがXのサブセットである

select v.variable, a.count(*), b.count(*) 
    from 
    (select x as variable 
    from my_table 
    union select y 
    from my_table) as v 
    inner join my_table as a on a.X = v.variable 
    inner join my_table as b on b.y = v.variable 
    group by v.variable 

によってあなたは労働組合の一時テーブルとグループを必要とするという事実を考えるには、労働組合を避けることができ、その後、とにかく、我々は明確なX

select v.variable, a.count(*), b.count(*) 
    from 
    (select distinct x as variable 
    from my_table) as v 
    inner join my_table as a on a.X = v.variable 
    inner join my_table as b on b.y = v.variable 
    group by v.variable 
が必要
+0

私はあなたが組合の後にselectのタイプミスをしたと思います。また、IMOは必要ありません。クエリを最適化する方法はありますか?2つの内部結合はテーブル上で多くの時間を費やしています。 – codeKNIGHT

+0

私はタイプミスをチェックして答えを更新しました.. optmizeのために..あなたはインデックス..キー(x、y)を考えることができます.. – scaisEdge

+0

何行ありますか? – scaisEdge

0
select variable,count(x),count(y) from 
(select distinct x as variable,x,y from my_table 
union all 
select distinct y as variable, x,y from my_table)v 
group by variable order by variable; 
+0

両方のカウントが同じです – codeKNIGHT

+0

ええ、それに取り組んで! – Priyanshu

関連する問題