-1

I am having trouble where my INNER JOIN duplicates data. I have a fault table and a media table which stores image filepaths.


Table 1: fault

Table 2: media

A user uploads their fault into table: fault, and then up to 7 images to support their application in to table: media. At present when 5 images say are uploaded, the fault data is repeated 5 times.


SELECT * FROM fault INNER JOIN media ON media.syncReportID = fault.faultID where faultID = {0}

This is ok but when you inner join something, everything is returned for every item in the joined table.

This SO suggests: DISTINCT- I get no exception but it does not work for me.

SELECT DISTINCT * FROM fault INNER JOIN media ON media.syncReportID = fault.faultID where faultID = {0}

This SO article here suggets: OUTER APPLY and GROUP BY but being honest I do not understand the complex syntax in these articles.

Can someone advise which SQL command would best suit the ability to allow many images to one story without duplicating the story many times over.

Is this even possible here?

Thanks in advance!

davvv
  • 772
  • 1
  • 6
  • 24

2 Answers2

1

I suspect that you want:

SELECT f.*, m.*
FROM fault f CROSS APPLY
     (SELECT TOP 1 m.*
      FROM media m
      WHERE m.syncReportID = f.faultID
     ) m
WHERE faultID = {0};

You would use OUTER APPLY if you always want exactly one row returned, even when there are no matching entries.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

You may need to specify the fields you want to be distinct like :

 SELECT DISTINCT fault.faultId,...... FROM fault INNER JOIN media ON media.syncReportID = fault.faultID where faultID = {0}
Eid Morsy
  • 966
  • 6
  • 8