douru5373 2017-11-13 00:38
浏览 138
已采纳

在While循环(php-mysql)中,我可以让它显示一个具有重复项的条目吗?

What I am trying to achieve is for instance I have a 2 companies that have posted 5 products. One company posted 1 product and the second company posted 4 products.

In my while loop it will show the first company that posted one product once and the second company that posted four products 4 times. What I want to do is have it just show the 2 companies that have posted products once. So if there are 5 companies all who have posted multiple products, they will not be multiplied by the amount of products they have posted but just display once as long as they have at least one product posted. Is it possible to achieve that from a query?

<?php
include("database.php");
$id=$_GET['id']; 
$query="SELECT * FROM dproducts, thevendor WHERE dproducts.vendor_id=thevendor.thevendor_id AND dproducts.active='1'"; 
$result=mysql_query($query) or die(mysql_error());
$num_rows = 0;
while($row = mysql_fetch_assoc($result))
{ 
$num_rows++;
?>
<br><?php echo $row['company_name']; ?><br>
<?php } ?>
  • 写回答

3条回答 默认 最新

  • dongqiao9394 2017-11-13 00:44
    关注

    Use aggregation to have those companies only who have at least one active product

    SELECT 
      v.* 
    FROM
      thevendor v 
      JOIN dproducts p 
        ON p.vendor_id = v.thevendor_id 
    WHERE p.active = '1' 
    GROUP BY v.thevendor_id 
    HAVING COUNT(p.vendor_id) > 0 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?