2015-01-11 54 views
0

我有一個產品表。看起來像這樣。sql查詢從產品列表中獲取小數量值

我希望我的輸出如下所示。 意味着只有單一的產品排在數量將是小


id Product Qty Rate 1 AAAA 200 100 1 AAAA 400 200 1 AAAA 800 400 2 BBBB 500 150 2 BBBB 1000 300
我需要這樣的輸出。只是一個產品的小數量顯示

 
     id  Product  Qty Rate 
     1  AAAA  200  100 
     2  BBBB  500  150 

我寫了這個查詢,但它可以是一個while循環的單個查詢。

$query="SELECT id FROM hproducts where category='".$category."'group by id order by qty"; 
    $result=mysql_query($query); 
    while($notic = mysql_fetch_array($result)) 
    {  
    $query2="SELECT id,productname,rate,qty,image FROM hproducts where id='".$noti['id']."'group by id,productname,rate,qty,image order by qty limit 1"; 
    $result2=mysql_query($query2); 
    while($noticia = mysql_fetch_array($result2)) 
    { 
    ... 
    } 
    } 

回答

1

試試這個查詢。

$query = " 
    select 
    p1.id, p1.rate, p1.qty, p1.image 
    from 
    hproducts p1 
    inner join (
     select id, min(qty) as qty from hproducts ps group by ps.id 
    ) p2 on p2.id = p1.id and p2.qty = p1.qty 
    where p1.category = '$category'"; 

子選擇得到最低量每產物,然後將其接合(並由此用作過濾器),用於的hProduct(別名P1)。

+0

謝謝您,先生,快速和正確的答案 –

相關問題