2017-07-14 51 views
0

Database-MySqlComplex sqlQuery

以下是create table語句。

CREATE TABLE `Test`(`T` varchar(40) DEFAULT NULL,`P` varchar(40) NOT NULL,`CT` char(1) DEFAULT 'V',`XY` char(1) DEFAULT 'A'); 

上表中有3列(T,P,CT,XY)。 1.在'T'列和'P'列有關係,這兩列的值會成對。該對中的任何值都不會與其他列的其他值配對。 2.列CT有3種可能的值---> V,W,X。 3.列XY有3種可能的值---> A,B,C。

表中的數據如下。

1. insert into Test values('T1','P1','V','A'); 
2. insert into Test values('T1','P2','V','B'); 
3. insert into Test values('T2','P3','V','C'); 
4. insert into Test values('T3','P3','V','A'); 
5. insert into Test values('T4','P4','V','A'); 
6. insert into Test values('T4','P4','V','A'); 
7. insert into Test values('T4','P4','V','B'); 
8. insert into Test values('T4','P4','W','A'); 
9. insert into Test values('T4','P4','X','A'); 

輸出將只有一個行 - T4,P4,2

說明

1. First row will be discarded because of T1 is making pair with 2 values(P1,P2)of Column 'P'. 
2. Second row will be discarded because of T1 is making pair with 2 values(P1,P2)of Column 'P'. 
3. Third row will be discarded because of P3 is making pair with 2 values(T2,T3)of Column 'T'. 
4. Fourth row will be discarded because of P3 is making pair with 2 values(T2,T3)of Column 'T'. 
5. Output will be pair of T4,P4 

輸出的第三列將被推導爲一對(T4,P4),計數列'CT'值爲V且列'XY'值爲A的實例數爲A.有2個實例(因爲您可以在第5行和第6行中看到),所以第三列輸出將是2.

I嘗試使用查詢,但它不是givi正確的結果。

select T,P,sum from (select T,P,sum(if(CT = 'A' and XY = 'B',1,0)) sum from Test group by T,P) X group by T having count(*)=1; 

什麼是Sql Query來解決上述問題?

+0

你可以嘗試更簡單的解釋你如何選擇行嗎? –

+0

也是一個更好的背景,它用於什麼目的。試圖使「通用」有時可以防止由於上下文的丟失。 – DRapp

回答

0

前四個在如何產生輸出說明的事項都可以通過使用聚合查詢發現,並排除,其中任TPTP所有獨特的組合中重複的情況下得到滿足,爲完成在這裏的子查詢:

select 
    t.T, t.P, count(*) as rows 
from 
    Test as t 
    left join (
     select T from (select distinct T, P from Test) as p1 group by T having count(*) > 1 
     ) as dupT on dupT.T=t.T 
    left join (
     select P from (select distinct T, P from Test) as p2 group by P having count(*) > 1 
     ) as dupP on dupP.P=t.P 
where 
    dupT.T is null 
    and dupP.P is null 
    and CT = 'V' 
    and XY = 'A' 
group by 
    t.T, t.P; 

這是您的標準相當字面解釋,丟棄壞的數據,但你也可以展開這項工作由包括只有良好的數據:

select 
    t.T, t.P, count(*) as rows 
from 
    Test as t 
    inner join (
     select T from (select distinct T, P from Test) as p1 group by T having count(*) = 1 
     ) as dupT on dupT.T=t.T 
    inner join (
     select P from (select distinct T, P from Test) as p2 group by P having count(*) = 1 
     ) as dupP on dupP.P=t.P 
where 
    CT = 'V' 
    and XY = 'A' 
group by 
    t.T, t.P; 
+0

很多時候'測試'表正在迭代,它可以最小化? –

+0

如果您的MySQL版本支持CTE,那麼將重複的子查詢「從測試中選擇不同的T,P」提取到CTE *中可能會提高性能。你可以使用'EXPLAIN'命令來檢查這個查詢計劃是否有這個改變。 「T」,「P」,「CT」和「XY」上的索引也可以提高性能。 –