swatisonee Posted October 20, 2011 Share Posted October 20, 2011 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." ; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/249447-unable-to-use-select-distinct-with-join/ Share on other sites More sharing options...
swatisonee Posted October 21, 2011 Author Share Posted October 21, 2011 Folks...anything you can spot on what might be going wrong with this code ? Much obliged. Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/249447-unable-to-use-select-distinct-with-join/#findComment-1281048 Share on other sites More sharing options...
jcbones Posted October 21, 2011 Share Posted October 21, 2011 Have you tried a scalar subquery? SELECT * FROM Customers WHERE CID = (SELECT DISTINCT(CID) FROM Reports LIMIT 1) ORDER BY Company Quote Link to comment https://forums.phpfreaks.com/topic/249447-unable-to-use-select-distinct-with-join/#findComment-1281202 Share on other sites More sharing options...
swatisonee Posted October 30, 2011 Author Share Posted October 30, 2011 Well this is what finally worked. SELECT * FROM Customers c RIGHT OUTER JOIN Reports r USING (CID) GROUP BY c.`Company` asc Thanks . S Quote Link to comment https://forums.phpfreaks.com/topic/249447-unable-to-use-select-distinct-with-join/#findComment-1283390 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.