Jump to content

Unable to use Select Distinct with Join


swatisonee

Recommended Posts

Hi: I have the foll. code. The table "Reports" has multiple records for a given value of CID in the Field CID. I'd like to be able to select only 1 of them so that a list of customers appearing in the Reports table is available for selection in the dropdown alphabetically.  The foll. code does it but it doesnt list the Customers alphabetically. And when I use Join, the query doesnt run. I get a blank list .  The Field CID is common to both tables- Reports and Customers.

 

Could someone help me with the Join ? Thanks. Swat

<?php

$sqlco =  "SELECT DISTINCT CID FROM `Reports` ";

$resultco = mysql_query($sqlco) or die (mysql_error() ) ;

if ($myrowco = mysql_fetch_array($resultco) )
{

  do {
$cid = $myrowco["CID"];
$sqlrep = "SELECT * FROM `Customers` WHERE `CID` = '$cid' " ;
$resultrep = mysql_query($sqlrep) or die (mysql_error() ) ;
$myrowrep = mysql_fetch_array($resultrep);
$company = $myrowrep["Company"];

     printf("<option value=%d>
      %s , %s", $myrowco["CID"], $myrowrep["Company"], $myrowco["Mdate"]);

  } while ($myrowco = mysql_fetch_array($resultco));

}

else 
{

echo "No records found." ;	
}

?></select></a>

 

What i tried was this :

 

<?php

$sqlco =  "SELECT DISTINCT CID FROM `Reports` r JOIN  `Customers` c  WHERE r.CID = c.CID ORDER BY c.Company asc ";

$resultco = mysql_query($sqlco) or die (mysql_error() );

if ($myrowco = mysql_fetch_array($resultco) )
{

  do {

     printf("<option value=%d>
      %s ", $myrowco["CID"], $myrowco["Company"]);

  } while ($myrowco = mysql_fetch_array($resultco));

}

else 
{

echo "No records found." ;	
}

?>

Link to comment
https://forums.phpfreaks.com/topic/249447-unable-to-use-select-distinct-with-join/
Share on other sites

  • 2 weeks later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.