分组或不同 - 我如何为3个表做

时间:2013-02-09 12:00:23

标签: sql image group-by sql-order-by

SELECT c.urun_id, a.kat_adi, b.resim_yolu, b.sira, 
c.urun_sira, c.urun_adi
FROM kategoriler a,resimler b, urunler c 
where  a.kat_id=c.kat_id and c.urun_id=b.urun_id
order by c.urun_sira,b.sira

urun_id = 17有两条记录。我想只返回一条记录。我有categoryproductsimages个表格。用户已在images表中添加了2张照片urun_id=17

但我想只显示一条在sira中具有最小值的记录。

如果查询的输出是

  • 25~pc~3
  • 17~phone~2
  • 17~phone~4

然后,我想返回

  • 17~phone~2

2 个答案:

答案 0 :(得分:0)

如果我理解你的问题,这应该有效,

SELECT c.urun_id, a.kat_adi, b.resim_yolu, min(b.sira),
       c.urun_sira, c.urun_adi
FROM kategoriler a,resimler b, urunler c
where a.kat_id=c.kat_id
and c.urun_id=b.urun_id
group by c.urun_id, a.kat_adi, b.resim_yolu,
       c.urun_sira, c.urun_adi
order by c.urun_sira,b.sira

答案 1 :(得分:0)

在SQLServer2005 +中使用ROW_NUMBER函数

 ;WITH cte AS
 (
  SELECT c.urun_id, a.kat_adi, b.resim_yolu, b.sira, 
         c.urun_sira, c.urun_adi, 
         ROW_NUMBER() OVER (PARTITION BY c.urun_id ORDER BY b.sira) AS rn
  FROM kategoriler a JOIN urunler c ON a.kat_id=c.kat_id
                     JOIN resimler b ON c.urun_id=b.urun_id
  )
  SELECT *
  FROM cte
  WHERE rn = 1
  ORDER BY urun_sira, sira

其他方式

  SELECT c.urun_id, a.kat_adi, b.resim_yolu, b.sira, 
         c.urun_sira, c.urun_adi         
  FROM kategoriler a JOIN urunler c ON a.kat_id=c.kat_id
                     JOIN resimler b ON c.urun_id=b.urun_id  
  WHERE EXISTS (
                SELECT 1
                FROM resimler r
                WHERE b.urun_id = r.urun_id
                HAVING MIN(r.sira) = b.sira
                )
  ORDER BY c.urun_sira, b.sira