sql匹配条件

时间:2011-04-01 12:03:38

标签: sql sql-server

我正在构建一个消息系统,允许我的客户根据他们的生物资料向客户发送消息..

我有以下表格

    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..

因此,Customer表链接到Customer Bio,其中包含所回答问题的答案。

基本上只需要客户1来,因为它是一个完全匹配而不是局部..我已经尝试了内/左连接..感觉就像一些简单的东西,但不能让我的头围绕它..

任何帮助非常感谢..

1 个答案:

答案 0 :(得分: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