Tuesday, 6 November 2018

Mysql: How do I decide when to use right joins/left joins or inner joins Or how to determine which table is on which side?

I know the usage of joins, but sometimes I come across such a situation when I am not able to decide which join will be suitable, a left or right.
Here is the query where I am stuck.
    SELECT  count(ImageId) as [IndividualRemaining],
                userMaster.empName AS ID#,
                CONVERT(DATETIME, folderDetails.folderName, 101) AS FolderDate,
                batchDetails.batchName AS Batch#,
                Client=@ClientName,
                TotalInloaded = IsNull(@TotalInloaded,0),
                PendingUnassigned = @PendingUnassigned,
                InloadedAssigned =     IsNull(@TotalAssigned,0),
                TotalProcessed = @TotalProcessed,
                Remaining = @Remaining
        FROM
                batchDetails
                    Left JOIN  folderDetails ON batchDetails.folderId = folderDetails.folderId
                    Left JOIN  imageDetails ON batchDetails.batchId = imageDetails.batchId
                    Left JOIN  userMaster ON imageDetails.assignedToUser = userMaster.userId

        WHERE   folderDetails.ClientId =@ClientID and verifyflag='n'
                and folderDetails.FolderName IN (SELECT convert(VARCHAR,Value) FROM dbo.Split(@Output,','))
                and userMaster.empName <> 'unused'

        GROUP BY userMaster.empName, folderDetails.folderName, batchDetails.batchName

        Order BY folderDetails.Foldername asc

 Answers


Yes, it depends on the situation you are in.
Why use SQL JOIN?
Answer: Use the SQL JOIN whenever multiple tables must be accessed through an SQL SELECT statement and no results should be returned if there is not a match between the JOINed tables.
In two sets:
  • Use a full outer join when you want all the results from both sets.
  • Use an inner join when you want only the results that appear in both sets.
  • Use a left outer join when you want all the results from set a, but if set b has data relevant to some of set a's records, then you also want to use that data in the same query too.

0 comments:

Post a Comment