[英]Group by or distinct - how can I do for 3 tables
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
There are two record with urun_id = 17
. 有两个记录
urun_id = 17
。 I want to return only one record. 我只想返回一条记录。 I have
category
, products
, images
tables. 我有
category
, products
, images
表。 User has added 2 photos in images
table where urun_id=17
. 用户在
images
表中添加了2张照片,其中urun_id=17
。
But I want to show only one record which has minimum value in sira
. 但是我只想显示一条在
sira
具有最低价值的记录。
If the output of the query is 如果查询的输出是
Then, I want to return 那我要回去
If I understood your question correctly, this should work, 如果我正确理解了您的问题,这应该可以解决,
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
In SQLServer2005+ use ROW_NUMBER function 在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
Other way 另一种方式
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.