简体   繁体   中英

Multiple joins to the first query across multiple tables

I always seem to get caught up in multiple joins. I have these tables that contain part numbers, then the descriptions for those part numbers are spread across 12 tables (I can't do anything about that). So I wanted to select only the part numbers I need, then get the descriptions for them by joining all 12 of those tables against my original query.

The result is the that only the first table's description, for the capacitors ever gets joined. The rest get lost, and I can comment out capacitors and get connectors, and so on down the list but I only ever get one at a time.

Is there a way to do this in SQL? Or am I missing the boat.

Here's my code:

        cmd.CommandText = "WITH PARTS AS(";
        cmd.CommandText += "SELECT *, ROW_NUMBER() OVER (ORDER BY p.PART_NUMBER) AS 'RowNumber'  FROM  dbo.AllParts AS p"; 
        cmd.CommandText += ")";
        cmd.CommandText += "SELECT * FROM PARTS as p "
        + "INNER JOIN dbo.[Component Manufacturer Parts] AS a ON p.RowID = a.PartGUID "
        + "INNER JOIN dbo.[Manufacturer Part Info] AS b ON a.ManufacturerGUID = b.RowID " 
        + "LEFT Join dbo.[CAPACITORS] as caps ON caps.RowID = p.RowID "
        + "LEFT Join dbo.[Connectors] as cons ON cons.RowID = p.RowID "
        + "LEFT Join dbo.[Crystals and Oscillators] as xtal ON xtal.RowID = p.RowID "
        + "LEFT Join dbo.[Diodes] as dio ON dio.RowID = p.RowID "
        + "LEFT Join dbo.[ICs] as ics ON ics.RowID = p.RowID "
        + "LEFT Join dbo.[Inductors] as ind ON ind.RowID = p.RowID "
        + "LEFT Join dbo.[Misc] as mis ON mis.RowID = p.RowID "
        + "LEFT Join dbo.[Relays] as rel ON rel.RowID = p.RowID "
        + "LEFT Join dbo.[Resistors] as res ON res.RowID = p.RowID "
        + "LEFT Join dbo.[Switches] as swi ON swi.RowID = p.RowID "
        + "LEFT Join dbo.[Transformers] as tra ON tra.RowID = p.RowID "
        + "LEFT Join dbo.[Transistors] as xfrm ON xfrm.RowID = p.RowID "                      
        + "WHERE RowNumber Between @low AND @high AND p.PART_NUMBER LIKE 'CT%'";

Thanks for any advice you can give.

The reason it doesn't work is because the first left join isn't returning anything to match with the second left join.

How about a view with the descriptions for all of the tables in a big union. It's pretty ugly but it would certainly be easier to query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM