douru5373
2017-11-13 08: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 } ?>

图片转代码服务由CSDN问答提供 功能建议

我想要实现的是例如我有2家公司发布了5个产品。 一家公司发布了1种产品,第二家公司发布了4种产品。

在我的while循环中,它将显示第一家公司发布一次产品,第二家公司发布四种产品4次。 我想做的就是让它只显示已经发布过一次产品的两家公司。 因此,如果有5家公司都发布了多个产品,那么它们不会乘以他们发布的产品数量,只要他们至少发布一个产品就会显示一次。 是否可以从查询中实现?

 &lt;?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)或die(mysql_error()); 
 $ num_rows = 0; 
while($ row = mysql_fetch_assoc($ result))
 {
 $ num_rows ++; 
?&gt;  
&lt; br&gt;&lt;?php echo $ row ['company_name'];  ?&gt;&lt; br&gt; 
&lt;?php}?&gt; 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongqiao9394 2017-11-13 08: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条)

相关推荐 更多相似问题