简体   繁体   English

MySQL - select 上的内部联接查询错误 1052

[英]MySQL - inner join on select query error 1052

Im trying to do a select query on a table along with an inner join afterwards to link data from the owner to the cats我试图在表上执行 select 查询以及随后的内部连接,以将数据从所有者链接到猫

the ownercat is using a foreign key on the id linking to the ownerinfo id ownercat 在链接到 ownerinfo id 的 id 上使用外键

USE CATTERY;
SELECT
OWNERINFO.ID, OWNERINFO.First_Name, OWNERINFO.Last_Name, OWNERINFO.Phone, OWNERINFO.AddrL1, OWNERINFO.AddrL2, OWNERINFO.AddrL3, OWNERINFO.PostCode,
GROUP_CONCAT(DISTINCT OWNERCAT.Chip_ID)
FROM OWNERINFO
INNER JOIN OWNERCAT ON OWNERINFO.ID = OWNERCAT.ID

WHERE ID = 1;

I get returned the following error: Error Code: 1052. Column 'ID' in where clause is ambiguous 0.0014 sec我收到以下错误:错误代码:1052。where 子句中的列“ID”不明确 0.0014 秒

removing the concat distinct statement still produces the same error, im not sure how to get around this issue删除 concat distinct 语句仍然会产生相同的错误,我不知道如何解决这个问题

You need to define from which table the ID on WHERE -clause come from (you can use aliases).您需要定义WHERE上的ID来自哪个表(您可以使用别名)。 Secondly, as you are using GROUP_CONCAT , you should have GROUP BY in the query:其次,当您使用GROUP_CONCAT时,您应该在查询中有GROUP BY

SELECT
  oi.ID, 
  oi.First_Name, 
  oi.Last_Name, 
  oi.Phone, 
  oi.AddrL1, 
  oi.AddrL2, 
  oi.AddrL3, 
  oi.PostCode,
  GROUP_CONCAT(DISTINCT oc.Chip_ID)
FROM OWNERINFO oi
  INNER JOIN OWNERCAT oc ON oc.ID=oi.ID
WHERE oi.ID = 1
GROUP BY oi.ID

The problem is in the WHERE clause: ID is ambiguous, because that column is available in both tables.问题出在WHERE子句中: ID不明确,因为该列在两个表中都可用。

You may think that, since you are joining the tables on ID , the database is able to tell that it has the same value, but that's not actually the case.您可能会认为,由于您正在加入ID上的表,因此数据库能够判断它具有相同的值,但实际上并非如此。

So just qualify the column in the WHERE clause, ie change this:因此,只需限定WHERE子句中的列,即更改此:

WHERE ID = 1

To either:至:

WHERE OWNERINFO.ID = 1

Or the equivalent:或等价物:

WHERE OWNERCAT.ID = 1

Also please note that your query uses GROUP_CONCAT() , which is an aggregate function.另请注意,您的查询使用GROUP_CONCAT() ,这是一个聚合 function。 This implies that you need a GROUP BY clause, that should list all non-aggregated column (ie all columns other than the one that is within GROUP_CONCAT() ).这意味着您需要一个GROUP BY子句,该子句应列出所有非聚合列(即除GROUP_CONCAT()中的列之外的所有列)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM