mysql匹配值的计数

gblwokeq  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(278)

我有一个有两列的数据库。character\u id和killmail\u id对象是获取特定character\u id的所有killmail\u id的列表,然后获取具有匹配killmail\u id的所有character\u id,并计算这些character\u id出现的次数
到目前为止,我得到了这个:($target是要搜索的字符\u id)

SELECT `character_id`, COUNT(`killmail_id`) FROM `attackers` WHERE $target NOT IN (SELECT `killmail_id` FROM `attackers` WHERE `character_id` <> $target) AND `character_id` <> $target  GROUP BY `killmail_id` ;

这几乎是可行的,但它计算一个角色拥有的killmail\u id的总数我只希望它计算killmail\u id,如果$target也有匹配的killmail\u id
如果没有意义的话,这就是我以前使用的(php),如果可能的话,我会尝试通过使用更具体的sql语句来消除循环。

function seenWith($target){
    $sql = "SELECT `killmail_id` FROM `attackers` WHERE character_id='" . $target . "';";
    $mySql = $db->prepare($sql);
    $mySql->execute();
    $results = $mySql->fetchAll();
    $friends = array();
    foreach ($results as $idx => $array){
        foreach ($array as $key => $value){
            $sql = "SELECT `character_id`,`killmail_id` FROM `attackers` WHERE killmail_id='$value' AND character_id<> '".$target."';";
            $mySql = $db->prepare($sql);
            $mySql->execute();
            $rData = $mySql->fetchAll();
            foreach($rData as $index => $friendName){
                array_push($friends, htmlspecialchars($friendName['character_id'], ENT_QUOTES));
            }
        }
    }
    return $friends;
}
9ceoxa92

9ceoxa921#

一个选项使用 exists :

select character_id, killmail_id
from attackers a
where
    character_id <> :target
    and exists (
        select 1
        from attackers a1
        where 
            a1.character_id = :target
            and a1.killmail_id = a.killmail_id
    )
``` `:target` 表示输入参数,您应该将其作为查询参数传递,而不是通过在查询字符串中串联它来传递。

相关问题