MySQL - Duplicate columns after using Join operator

放肆的年华 提交于 2019-12-12 04:57:17

问题


As stated in the title, I'm getting duplicate columns with this JOIN query. A few tables are given and I want to write select statements to get only the information from the tables which are needed.

Here is my SQL code so far:

    SELECT mitarbeiter.PNR, pfleger.PNR, Name
    from pfleger
    JOIN mitarbeiter on (mitarbeiter.PNR=pfleger.PNR)
    where Ort='Frankfurt';

After executing, I get the following result:

You can see the problem: I have two PNR columns which I don't want to have. How can I remove the duplicate? I have tried SELECT DISTINCT ... but it doesn't accomplish my goal.


回答1:


Just remove one from the select:

SELECT mitarbeiter.PNR, Name from pfleger JOIN mitarbeiter on (mitarbeiter.PNR=pfleger.PNR) where Ort='Frankfurt';



回答2:


select distinct applies to rows, not columns. In the column list, just select one of the PNR columns:

SELECT mitarbeiter.PNR, Name from pfleger JOIN mitarbeiter on (mitarbeiter.PNR=pfleger.PNR) where Ort='Frankfurt';



回答3:


In the select portion of the statement reference the PNR column from either of the tables (mitarbeiter, pfleger), but not both:

SELECT 
  mitarbeiter.PNR, 
  Name 
from pfleger JOIN mitarbeiter on (mitarbeiter.PNR=pfleger.PNR) 
where Ort='Frankfurt';



回答4:


As other users have already mentioned, you just need to remove a field name from the SELECT clause. I just want to add that if the field you join on has the same name in both tables you can use special syntax, which allows to reference both columns as a single one:

SELECT PNR, Name
from pfleger
JOIN mitarbeiter USING (PNR)
where Ort='Frankfurt';


来源:https://stackoverflow.com/questions/34277033/mysql-duplicate-columns-after-using-join-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!