简体   繁体   中英

Using part of a previous sql select in a later select

So I am trying to use part of the results of a select statement in a second and third select after the results have been set to a variable

$result = $db->query('SELECT operator, COUNT(DISTINCT dupi), COUNT(DISTINCT userID), dupi FROM reported GROUP BY operator ORDER BY COUNT(DISTINCT userID) DESC');

foreach($result as $row)
{
  $result2 = $db->query('SELECT dupi FROM reported WHERE operator = $row['operator']');

  $result3 = $db->query('SELECT dupi FROM reported WHERE operator = $row['operator'] AND dupi != NULL');

I don't know if this is possible but I am wanting to do this so I can do an if statement later in the code

Try this:

$result = $db->query('SELECT operator, COUNT(DISTINCT dupi), COUNT(DISTINCT userID), dupi FROM reported GROUP BY operator ORDER BY COUNT(DISTINCT userID) DESC');

foreach($result as $row)
{
    $result2 = $db->query("SELECT dupi FROM reported WHERE operator = " . $row['operator']);
    $result3 = $db->query("SELECT dupi FROM reported WHERE operator = " . $row['operator'] . " AND dupi != NULL");
}

If it works it was just a concatenation problem with 'SELECT...$row['

One way to debug this kind of problem:

foreach($result as $row)
{
    // You write the query in a string
    $sql2 = "SELECT dupi FROM reported WHERE operator = " . $row['operator'];

    var_dump($sql2); // Check how it looks

    $result2 = $db->query($sql2);

    // same for $result3
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM