Column ' ' in field is ambiguous

2019-09-07 03:19发布

问题:

Im working with MySQL in java.

I'm trying to update the 'owners' field in one of the tables 'regApartmentsTable', 'gardApartmentsTable', 'penthousesTable', which is empty, and corresponds to specific apartmentNum and street, and replace it with the string 'newOwners'.

In order to do that I've wrote the following code:

st=connection.prepareStatement("UPDATE regApartmentsTable,gardApartmentsTable,penthousesTable SET owners=? " +
                "WHERE owners=? AND apartmentNum=? AND street=?");
st.setString(1, newOwners);
st.setString(2, "");
st.setInt(3, apartmentNum);
st.setString(4, streetName+" "+buildingNum);

I include the 3 tables since I need to look in all of them. (The required apartment, which has no owners, and matches the apartmentNum and street, cannot be in more than one table, if it helps anyone).

But, when I try to run this code, I get a "Column 'owners' in field is ambiguous" error. Any ideas how else should I write the SQL command ? thanks ahead!

EDIT: I didn't get a sufficient answer to my problem... Ok, I understood that the exception raises since 'owners' field is common in those three tables. And yet, how do I solve the problem? I cannot add a prefix with the table's name since I do not know in which table I'm going to find the required apartment... If I knew so, I wouldn't have searched in 3 tables.

回答1:

The multiple tables UPDATE in MySQL is just a form of table join, using regApartmentsTable.owners and such.

You need a separate UPDATE for every table here, as a join is not what you intend for the update. Or make a base table.

str = connection.prepareStatement("UPDATE regApartmentsTable SET owners=? " +
                "WHERE owners=? AND apartmentNum=? AND street=?");
str.setString(1, newOwners);
str.setString(2, "");
str.setInt(3, apartmentNum);
str.setString(4, streetName+" "+buildingNum);

str = connection.prepareStatement("UPDATE gardApartmentsTable SET owners=? " +
                "WHERE owners=? AND apartmentNum=? AND street=?");
stg.setString(1, newOwners);
stg.setString(2, "");
stg.setInt(3, apartmentNum);
stg.setString(4, streetName+" "+buildingNum);

stp = connection.prepareStatement("UPDATE penthousesTable SET owners=? " +
                "WHERE owners=? AND apartmentNum=? AND street=?");
stp.setString(1, newOwners);
stp.setString(2, "");
stp.setInt(3, apartmentNum);
stp.setString(4, streetName+" "+buildingNum);