从邀请中选择conversationId

时间:2011-03-12 18:31:04

标签: php mysql

我有一个会话表和一张受邀表。会话表存储了所有消息以及conversationId(不需要知道更多)。受邀表有两列名为conversationId和profileId。我想选择与邀请列表匹配的conversationId。我如何在MYSQL和PHP中做到这一点?

到目前为止,我已经在PHP中完成了这个:

 $sql = "
    SELECT invited.conversationId, count(invited.conversationId) AS cof
    FROM conversation_invited AS invited 
    WHERE   invited.profileId = '$profileId'//This is myself
    ";
    $i = 0;
    foreach($invited as $v){//$invited is an array of invited's profileIds
            $sql .= "
    AND     invited.profileId = '$v' ";
        $i++;
    }

    $sql .= "
    GROUP BY invited.conversationId
    ORDER BY count(invited.conversationId) ASC
    LIMIT 1
";

我想要创建的sql语句想要完全匹配邀请。例如,如果被邀请的数组由['27','34','36']组成,那么我想要找到与被邀请数组完全匹配的对话(Id)。邀请也不少,也不多。

2 个答案:

答案 0 :(得分:0)

试试这个

$invites = join(',', array_merge($invited, (array)$profileId))
$sql = "
    SELECT invited.conversationId, count(invited.conversationId) AS cof
    FROM conversation_invited AS invited 
    WHERE invited.profileId IN($invites)
    GROUP BY invited.conversationId
    ORDER BY count(invited.conversationId) ASC
    LIMIT 1
";

答案 1 :(得分:0)

function add_quotes(&$item) {
    $item = "'$item'";
} 
array_walk($invited, 'add_quotes'); 
$t = implode(',', $invited);
$sql = "
    SELECT invited.conversationId, count(invited.conversationId) AS cof
    FROM conversation_invited AS invited 
    WHERE invited.profileId IN ('$profileId', $t)
    GROUP BY invited.conversationId
    ORDER BY count(invited.conversationId) ASC
    LIMIT 1
";

请注意,上述内容将更改$invited中的值。