Domanda

There are a lot of questions already regarding this, however I have not found any that address my particular issue. I am running a check on a MySQL Database and if more than 1 row has the same BILLING_ID, I want to print it out as these should be unique with rare exception.

I however need to exclude duplicates when they have a GAME_ID of different values, as we do set child services with the same billing ID.

My code below works for the most part until logic fails me. If there are 2+ entries with the same Billing ID, I need to check whether they have the same GAME_ID or not. I stumped myself with this one and cannot figure out how to proceed.

$res_services = mysql_query('SELECT SERVICE_ID, BILLING_ID, USER_ID, GAME_ID FROM tc_services', $tca_conn);

while ($row_services = mysql_fetch_array($res_services))
{
    $service_id = $row_services["SERVICE_ID"];
    $billing_id = $row_services["BILLING_ID"];
    $user_id = $row_services["USER_ID"];
    $game_id = $row_services["GAME_ID"];

    // If the Billing ID field is blank, ignore
    if ($billing_id == "")
    {
        continue;
    }

    $res_dupes = mysql_query("SELECT * FROM tc_services WHERE BILLING_ID='" . $billing_id . "'", $tca_conn);
    $num_rows = mysql_num_rows($res_dupes);

    if ($num_rows >= 2)
    {
        while ($row_dupes = mysql_fetch_array($res_dupes))
        {
             //check if GAME_ID is different
        }

        echo 'Duplicate Services found for User ID: ' . $user_id . 'Billing ID: ' . $billing_id . '</br>';
    }
}
È stato utile?

Soluzione

Instead of looping and making multiple calls, just use a single database call

The subquery X identifies duplicates of BILLING_ID, GAME_ID.
Then we join back to get USER_ID

Note: you must use this standard SQL and not the inane MySQL GROUP BY extensions

SELECT
    t.BILLING_ID, t.USER_ID
FROM
    (
    SELECT
        BILLING_ID, GAME_ID, COUNT(*)
    FROM
        tc_services
    GROUP BY
        BILLING_ID, GAME_ID
    HAVING
        COUNT(*) > 1
    ) X
    JOIN
    tc_services t ON X.BILLING_ID = t.BILLING_ID AND X.GAME_ID = t.GAME_ID

Altri suggerimenti

Instead of this

$res_dupes = mysql_query("SELECT * FROM tc_services WHERE BILLING_ID='" . $billing_id . "'", $tca_conn);

Use this :

$res_dupes = mysql_query("SELECT * FROM tc_services WHERE BILLING_ID='" . $billing_id . "' AND GAME_ID='" . $game_id . "'", $tca_conn);

You can check game id in same select query.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top