How to test in and between each of several tables?

前端 未结 2 1499
傲寒
傲寒 2021-01-29 03:48

I know this is too simple for most here, but I just can\'t figure it out from the 3 books I am using or find it in a tutorial. They all focus on changing the layout of a databa

2条回答
  •  -上瘾入骨i
    2021-01-29 04:16

    Well Leonid is right table joins is what you need. "An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them." - http://www.w3schools.com/sql/sql_join.asp simple as that. You say for table A and table B that common field is the ShopLot and for table B and C is the ContainerRef matches the ContainerID.

    Let's tray do that step by step.

    So first lets select columns from the tables we want to show

     SELECT Table_A.ID, Table_A.UnitTypeID, Table_A.ShopLot, Table_B.ID, Table_B.UnitTypeID,
             Table_B.ContainerRef, Table_C.ID, Table_C.PartTypeID
    

    You see there is only one the ShopLot and the ContainerRef that's becouse that is common field as we said before and there is no need to show the same date twice in one row.

    Next step would be to see where FROM we SELECT this columns. In this step we combine rows from this separate tables and basically create one table with all this columns from select statement. That will look like this

    FROM Table_A
    INNER JOIN Table_B
    ON Table_A.ShopLot = Table_B.ShopLot
    INNER JOIN Table_C
    ON Table_B.ContainerRef = Table_C.ContainerId
    

    What's happened here. First we said SELECT(something) FROM Table_A and (inner) join her with Table_B... Then there is a question how to join this two table (based on what?)? And the answer is ON Table_A.ShopLot and Table_B.ShopLot fields. Take a row from Table_A, see value of ShopLot field and find all rows with that value (if there is) in Table_B and join them. Table_C is joined the same way only name of fields is changed.

    Than the third step is to make WHERE clause. This is probably the easiest part because we now have one large table and we just need to say what we need

    WHERE Table_A.UnitTypeID='PAD' AND Table_B.UnitType.ID='FROG' 
      AND Table_C.PartTypeID='FLIES'
    

    And that's it. I tried to make it simple as i could. I bet there is much bather explanation online just need to do a little search...

    Here is a complete code:

    SELECT Table_A.ID, Table_A.UnitTypeID, Table_A.ShopLot, Table_B.ID, Table_B.UnitTypeID,
             Table_B.ContainerRef, Table_C.ID, Table_C.PartTypeID
    FROM Table_A
    INNER JOIN Table_B
    ON Table_A.ShopLot = Table_B.ShopLot
    INNER JOIN Table_C
    ON Table_B.ContainerRef = Table_C.ContainerId
    
    WHERE Table_A.UnitTypeID='PAD' AND Table_B.UnitType.ID='FROG' 
      AND Table_C.PartTypeID='FLIES'
    

    I hope this help a little bit it's not complicated as it's look at first. It would be better if example be with two table but it is what it is. GL

提交回复
热议问题