2016-04-09 95 views
1

我可以簡單地選擇,加入,更新查詢。但是這對我來說似乎有點困難(我只是在學習)。使用自加入的SQL查詢

客戶有這樣的表(使用Mysql)(我沒有控制他的數據庫模式,我無法爲他創建Customers表,我只需要創建一些客戶報告)。

+-----------+--------------+--------------------------+ 
|Transaction|Customers name|Customers email |Set | 
+-----------+--------------+--------------------------+ 
| 1   | John   | [email protected]  | blue | 
| 2   | Mary   | [email protected]  | green | 
| 3   | Paul   | [email protected]  | red | 
| 4   | JOHN G.  | [email protected]  | green | 
| 5   | Paul Simon | [email protected]  | blue | 
+-----------+--------------+--------------------------+ 

正如您所看到的,每次交易客戶都可以自由輸入他的名字。這可能會導致顯然更多的客戶,但電子郵件領域是獨一無二的。

我需要這些報告(所有的人都被他買的驅動 - 在「設置」字段):

1)和searchs(如「藍」和「綠」) 客戶已經購買了'這個'和'那個'。 我需要得到這樣的結果:

|John  | [email protected] | 

或本(正如我所說,約翰可以輸入自己的名字不同的方式每一筆交易如果電子郵件是獨一無二的,它是好的。):

|JOHN G. | [email protected] | 

2)或searchs(如 '藍色' 或 '紅色') 需要得到這個:

|John  | [email protected] | 
|Paul  | [email protected] | 

或本:

|John  | [email protected] | 
|Paul Simon| [email protected] | 

3)買一組,而不是其他(如 '綠色',但不是 '藍色')

|Mary  | [email protected] | 

Doe的人知道如何做到這一點?我相信這可以通過某種「自我加入」來實現。但是,因爲我只是一個初學者,我無法弄清楚如何解決這個問題。

+0

你想在一個查詢中進行所有這些搜索嗎? –

+0

不,我需要3個查詢... – Liz

回答

1

很明顯,一個人可以購買這套或那套,我想甚至有可能一個人在以後的交易中再次購買相同的套裝。

所以你想要每個人的信息。最簡單的方法是通過個人分組來彙總數據(GROUP BY)。然後,您檢查HAVING條款中的彙總:通過設置X和/或y來完成客戶嗎?

查詢1:

select email, name 
from transactions 
group by email 
having max(case when set = 'blue' then 1 else 0 end) = 1 
    and max(case when set = 'green' then 1 else 0 end) = 1; 

查詢2:

select email, name 
from transactions 
group by email 
having max(case when set = 'blue' then 1 else 0 end) = 1 
    or max(case when set = 'red' then 1 else 0 end) = 1; 

查詢3:

select email, name 
from transactions 
group by email 
having max(case when set = 'green' then 1 else 0 end) = 1 
    and max(case when set = 'blue' then 1 else 0 end) = 0; 

你個獲得名稱ese查詢只是任意選擇的匹配名稱之一。這在MySQL中是很特別的。在標準的SQL中,這是不允許的。無論如何,無論是MySQL還是標準SQL,您也可以使用MIN(name)MAX(name)來始終按字母順序獲取第一個或最後一個。

順便說一句:CASE WHEN表達式是標準的SQL。然而,MySQL具有額外的特殊布爾操作:真正的表達式計算爲1,虛假表達式計算爲0.因此,在MySQL中,您可以簡單地編寫max(set = 'green') = 1而不是max(case when set = 'green' then 1 else 0 end) = 1

+0

嗨Thorsten。感謝您的貢獻。我沒有得到查詢1和查詢3的區別。他們看起來和我很相似。正如我所說,在查詢3中,我需要那些買了一套但不是另一套的顧客。 – Liz

+0

糟糕,錯字。當然,這應該是綠色= 1(是),藍色= 0(否)。糾正。 –

+0

現在它是有道理的。感謝您的貢獻。我會試一試。 – Liz

1

對於第一次查詢 - 我在這裏使用

select name,email from customer c where Set = 'blue' and c.email = (select email from customer where Set = 'green' and email = c.email); 

對於第二子查詢查詢 - 簡單或條件將圍繞足夠

select * from customer where Set = 'green' or Set = 'blue' group by email ; 

第三的query(它的工作,根據您的要求它會工作,它是基於像應該只有1條記錄的方法,並且該記錄應該具有設置值,如輸入中所提​​到的那樣)

select * from customer group by email having count(pset)= 1 and pset like 'green'; 
+0

哇!很快Narendra,非常感謝你!這解決了查詢1和2的問題。但我仍然需要第三個查詢(但不是那個...)。 – Liz

+0

如果它解決了你的問題,你可以upvote/accept。 –

+0

非常好!從來沒有碰到過這麼快得到幫助! – Liz