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
Share on other sites

  • 2 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.