Forum Moderators: coopster

Message Too Old, No Replies

PHP Query

PHP Query

         

shimeal

6:47 pm on Jan 13, 2005 (gmt 0)

10+ Year Member



I have a database listing multiple names under a brand that are divided into two types (i.e. HP is the brand, inkjet and laser are the types, and C41527X is one of the names under HP laser). I want to run a query that will show ONLY ONCE the Brand and the Type. Right now, with the following query (listed below), the Brand and the Type will show up multiple times (depending upon how many name entries are associated with both).

I want the query to display something like this:

Brand 1...Type 1
Brand 1...Type 2
Brand 2...Type 1
Brand 2...Type 2
Brand 3...Type 1
Brand 4...Type 1
Brand 5...Type 1
Brand 5...Type 2

There are approx. 10 Brands and 2 Types in my database. However, not every brand is associated with both types. If not type is associated with the brand, I do not want to display it. Thanks!

<?
$sql = "SELECT t.type, n.name, b.brand FROM cart_number n, cart_type t, cart_brand b WHERE n.type_id=t.type_id AND b.brand_id=n.brand_id ORDER BY brand, type, name";
$result = mysql_query($sql, $db);
while($row = mysql_fetch_assoc($result)) {
?>
<tr>
<td width="50%" align="center" class="content_text"><? echo stripslashes($row['brand']);?></td>
<td width="50%" align="center" class="content_text"><? echo stripslashes($row['type']);?></td>

</tr>
<? }
mysql_free_result($result);
?>

mcibor

8:37 pm on Jan 13, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Just add keyword DISTINCT

$sql = "SELECT DISTINCT t.type, n.name, b.brand FROM cart_number n, cart_type t, cart_brand b WHERE n.type_id=t.type_id AND b.brand_id=n.brand_id ORDER BY brand, type, name";

This should do.
Another option is keyword GROUP BY

$sql = "SELECT t.type, n.name, b.brand FROM cart_number n, cart_type t, cart_brand b WHERE n.type_id=t.type_id AND b.brand_id=n.brand_id GROUP BY brand, type, name";

Hope this helped you somehow
Best regards!

Michal Cibor

And even the mirrors shall be on our side

shimeal

3:44 am on Jan 14, 2005 (gmt 0)

10+ Year Member



Thanks - I had to take out the "name" portion from GROUP BY... but after that it worked great!