php帮助中的mysql查询/计数 - 计算与ID不同的出现次数

时间:2016-05-21 01:21:36

标签: php mysql counting

我们说我们有两张桌子:

users
id     login     password
1      user1     $432rget5343
2      user2     $432rget5343
3      user3     $432rget5343


trips
id     date         driver_id      passengers
1      19-05-2016   1              [2][3]
2      19-05-2016   2              [1][3]
3      19-05-2016   1              [2][3]
4      19-05-2016   1              [2]

基本上,整个剧本的目标是跟踪驾驶在少数人群中工作。每天都有其他人开车(driver_id) 我需要以某种方式计算下一个应该开车的人。 以上是我提出的表格,大部分剧本已经完成,但我仍然坚持计算这个。

从上表中,所需的输出应为:

  1. 驾驶员身份1驾驶乘客2和3因此身份2和3的人欠" 1"到id为1的那个

  2. ID 2的家伙这次开车,所以他对ID 1的家伙的反击现在为零,而现在的乘客3#34欠了#34; id为1 +1,id-2为+1

  3. id 1再次是一个驱动程序,所以现在id 2的id为1,而id为3的人现在为#34;欠" id为

  4. 的驱动程序为+2
  5. 1再次是司机,但他只带一名乘客,因此现在身份为2的家伙"欠#34; ID为1的+2

  6. 我希望我的解释清楚。对不起,你必须阅读那么多。 数据与上面的转储中的数据完全相同(使用方括号等)

    知道如何以正确的方式做到这一点吗?

1 个答案:

答案 0 :(得分:0)

假设您无法更改数据库结构并且您正在使用MySQL,那么您可以这样做:

// Set up the connection to the database
$mysqli = new mysqli(HOST, USER, PASS, DBNAME);

// Execute the query
$results = $mysqli->query('SELECT driver_id, passengers FROM trips');

// Here we store all trips records
$records = [];

// Loop through all results
while($row = $results->fetch_array())
{
    $driver_id = $row[0];

    // If the driver id is not in the records, we add it
    if(!array_key_exists($driver_id, $records))
    {
        $records[$driver_id] = [];
    }

    // We parse the passenger string and retrieve an array with the ids
    $passengers = explode('[', substr(str_replace(']', '', $row[1]), 1));

    // We check every passenger
    foreach ($passengers as $passenger) {

        $passenger_id = intval($passenger);

        // As the driver drove the passenger, he owes -1 to him
        $records[$driver_id][$passenger_id]--;

        // If the passenger's id is not in the records, we add it
        if(!array_key_exists($passenger_id, $records))
        {
            $records[$passenger_id] = [];
        }

        // We update the passenger debt towards the driver
        $records[$passenger_id][$driver_id]++;
    }

}

foreach($records as $id => $record)
{
    foreach($record as $other_id => $iou)
    {
        // We are only interested in positive values
        if ($iou > 0)
            echo "Driver #$id owes driver #$other_id $iou trip(s)</br>";
    }
}

这将为您提供以下输出:

Driver #2 owes driver #1 2 trip(s)
Driver #3 owes driver #1 2 trip(s)
Driver #3 owes driver #2 1 trip(s)