Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

How can I select 4 distinct values from 2 tables containing many rows of data in SQL Server?

I have 2 tables that Im trying to select 4 results from ordered by GalleryID DESC. The fields Im looking to return are GalleryID, GalleryTitle, GalleryDate from the Galleries table, and MediaThumb from the Media Table.

Now the catch is that the Media table has multiples of 10 of GalleryID's. So, there could be 10 rows in the Media table with the same GalleryID. All I need is one MediaThumb to go along with the galleryid.

Im not sure how to formulate a query to return 4 distinct galleryid's from the galleries table and a MediaThumb from the media table.

Essentially what im trying to do is return 4 unique photo galleries with a cover photo from the media table.

Any help would be appreciated. I provided a snapshot via query designer in sqlserver of my 2 tables.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like this?

SELECT TOP 4 
    g.GalleryID
    ,g.GalleryTitle
    ,g.GalleryDate
    ,MAX(m.MediaThumb) AS MaxMediaThumb
FROM Galleries g
    INNER JOIN Media m
        ON g.GalleryID = m.GalleryID
GROUP BY g.GalleryID, g.GalleryTitle, g.GalleryDate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...