问题
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