MySQL Removing duplicate columns on Left Join, 3 tables

后端 未结 4 460
时光取名叫无心
时光取名叫无心 2020-12-06 05:42

I have three tables, each have a foreign key. When I perform a join, I get duplicate columns.

Given

mysql> describe Family;
+---------------+----         


        
相关标签:
4条回答
  • 2020-12-06 06:18

    You are not getting duplicate columns, what you are really getting is the Supervisor_ID column from table Family (that is Family.Supervisor_ID) and Supervisor_ID from table Supervisor (that is Supervisor.Supervisor_ID) but to your result set, you will see both as Supervisor_ID, and that is why you think they are duplicated. The same will happen with Center_iD.

    The solution is to specify the fields that you need from each table, and decide if you need to get the Supervisor_ID and Center_ID and which table to get it from.

    0 讨论(0)
  • 2020-12-06 06:20

    By default MySQL will return all columns for all tables if you use *. You will need to explicitly enter column names in your query to retrieve them the way you want. Use the query as follows:

    SELECT A.HEAD_name, A.Family_Size, A.Gender, A.ID_Number, A.DOB,
        B.Supervisor_ID, B.Supervisor_Name, B.Supervisor_Number,
        C.Center_ID, C.Location
    FROM Family A
    JOIN SUPERVISOR B on ( A.Supervisor_ID = B.Supervisor_ID)
    JOIN CENTER C on (B.Center_ID = C.Center_ID);
    
    0 讨论(0)
  • 2020-12-06 06:23

    The problem can be solved by "USING" keyword.

    SELECT * from Family
       JOIN SUPERVISOR on ( Family.Supervisor_ID = SUPERVISOR.Supervisor_ID)
       JOIN CENTER on (SUPERVISOR.Center_ID = CENTER.Center_ID); 
    

    In your case the query will become

    SELECT * FROM FAMILY 
      JOIN (SUPERVISOR JOIN CENTER USING(Center_ID)) USING(Supervisor_ID);
    

    The point is Simple, If you have two Tables A(a,b) and B(b,c) then after joining to produce the result in the form of (a,b,c)

    Select *
        from A JOIN B USING(b);
    

    will give the Result-Set with three columns(a,b,c)

    NOTE : Since I don't know whether we can use multiple params in Using, therefore I made it as subquery.

    0 讨论(0)
  • 2020-12-06 06:35

    According to oreilly,

    Look for an explain plan.
    You can do a _select x from y inner join.... where w=z ... this is just an example

    0 讨论(0)
提交回复
热议问题