SQL Server – Sélectionnez un logging random ne montrant pas les duplicates

J'ai deux tables, des events et des photos, qui se rapportent set via la colonne 'Event_ID'. Je souhaite sélectionner UNE photo random de chaque événement et les afficher.

Comment puis-je faire ceci?

J'ai ce qui suit qui affiche toutes les photos qui sont associées. Comment puis-je le limiter à un par événement?

SELECT Photos.Photo_Id, Photos.Photo_Path, Photos.Event_Id, Events.Event_Title, Events.Event_StartDate, Events.Event_EndDate FROM Photos, Events WHERE Photos.Event_Id = Events.Event_Id AND Events.Event_EndDate < GETDATE() AND Events.Event_EndDate IS NOT NULL AND Events.Event_StartDate IS NOT NULL ORDER BY NEWID() 

Merci

Luke Stratton

Vous pouvez utiliser une cross apply pour récupérer une photo random par événement:

 select * from Events cross apply ( select top 1 * from Photos where Photos.Event_Id = Events.Event_Id order by newid() ) RandomPhoto where Events.Event_EndDate < GETDATE() and Events.Event_EndDate IS NOT NULL and Events.Event_StartDate IS NOT NULL 

Utilisez une outer apply si vous souhaitez récupérer des events sans photos.

Regardez cet article xaprb . Il montre plusieurs techniques que vous pourriez utiliser. Il recommand une approche de ligne minimale et d'auto-adhésion.