Jump to content

Displaying records from 2 tables.


theITvideos

Recommended Posts

Hi  there.

 

I am working on 2 tables:


  • Supplier
  • Products
     

Every supplier has multiple Products under them. I need to display only 1 Product from every Supplier.

 

What query would be better. I am not very good with queries.

 

Do we use some nested queries to display only 1 Product from every Supplier?

 

Any comment or feedback are always welcomed. :)

 

Thank you!

 

 

 

Link to comment
Share on other sites

Hi

 

You really need to specify which one you want returned

 

Just guessing on column names

 

SELECT a.SupplierName, b.ProductName
FROM Supplier a
INNER JOIN (SELECT SupplierId, Max(ProductId) AS MaxProdId FROM Products GROUP BY SupplierId) b ON a.SupplierId = b.SupplierId
INNER JOIN Products c ON b.MaxProdId = c.ProductId

 

That will get a list of supplier names with a product name for each where the product id is the highest one for that supplier.

 

All the best

 

Keith

Link to comment
Share on other sites

My best idea at randomizing a product would be:

 

$query = "SELECT SupplierID FROM Suppliers";
$result = mysql_query($query);

while($row = mysql_fetch_array($result)){

  $query2 = "SELECT COUNT(*) FROM Products WHERE SupplierID = '".$row['SupplierID']."';
  $result2 = mysql_query($query2);

  $count = mysql_result($result2, 0);
  $number = rand(0, ($count - 1));

  $query3 = "SELECT Supplier.SupplierName, Products.ProductName FROM Supplier INNER JOIN Products ON Supplier.SupplierId = Products.SupplierId WHERE SupplierID = '".$row['SupplierID']."'";
  $result3 = mysql_query($query3);

  $display = mysql_result($result3, $number);
  echo $display;

}

 

This is assuming also that the table Products and Supplier both have a SupplierID which is the Foreign key linking them together. And also assuming that Suppler has SupplierName, which is what you wanted to display.

Link to comment
Share on other sites

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.