2011-04-01 92 views
2

我建立一個信息系統,使我的客戶將消息發送到基於其生物知名客戶..SQL匹配標準

我有以下表

message 
    -------- 
    id(pk) 1 
    message 'This is a message' 

    message_bio 
    --------- 
    idPK question_id answer_id message_id (fk for message table) 
    1  1    4   1 
    2  2    3   1 
    3  3    2   1 

    customer_bio 
    ------------- 
    id customer_id question_id answer_id 
    1  1   1    4 
    2  1   2    3 
    3  1   3    2 
    4  2   1    4 
    5  2   2    3 
    6  2   3    6 

    question_table 
    id  question 
    1  gender etc.. 

因此客戶錶鏈接到客戶生物,其中有答案的問題的答案..

基本上只需要客戶1來,因爲它是一個完整的匹配不是部分..我試過內/左連接..感覺像一些簡單,但不能讓我的頭靠近它..

不勝感激任何幫助..

+0

我不知道你在這裏試圖做什麼。哪些是customer_bio和message_bio中的主鍵?你如何將一個與另一個聯繫起來?什麼是bio_q和bio_a?而不是用虛擬數據顯示示例行,請描述表結構和**它們之間的關係**。然後人們可以更好地瞭解你在這裏完成的任務。 – 2011-04-01 12:10:31

+0

message_bio和customer_bio不直接相關..他們是通過問題和答案..因此,例如..消息需要發送到性別= 1,職業= 2,favourite_food = 4它需要找到誰擁有的客戶完全匹配 – Alessandro 2011-04-01 12:53:49

回答

3

如果我理解你想找到有關於該消息的所有問題一樣答案customer_bio記錄你的問題。

爲了做到這一點,您需要將客戶問題的數量與匹配郵件記錄的數量進行比較。

SELECT c.*, m.* 
FROM customer c 
     INNER JOIN (SELECT mb.message_id, 
          cb.customer_id, 
          COUNT(mb.question_id) match_count 
        FROM customer_bio cb 
          INNER JOIN message_bio mb 
          ON cb.question_id = mb.question_id 
           AND cb.answer_id = mb.answer_id 
        GROUP BY mb.message_id, 
          cb.customer_id) message_matches 
     ON c.customer_id = message_matches.customer_id 
     INNER JOIN (SELECT cb.customer_id, 
          COUNT(cb.question_id) 
        FROM customer_bio 
        GROUP BY customer_id) customer_count 
     ON message_matches.customer_id = customer_count.customer_id 
      AND message_matches.match_count = customer_count.customer_count 
     INNER JOIN messages m 
     ON m.message_id = message_matches.message_id