使用INNER JOIN和WHERE进行SQL查询

时间:2013-08-21 12:50:08

标签: mysql sql database ms-access

尝试在查询中获取特定值时,我收到以下消息

“指定的字段可以引用多个表”

很明显,我正在尝试搜索多个表中存在的内容,但是如何做到这一点呢?

现在我有以下代码:

SELECT Table1.CustomerId, Table1.Address, 
       Table2.CustomerId, Table2.Telephone, 
       Table3.CustomerId, Table3.Notes
FROM (Table1 INNER JOIN Table2 ON Table1.CustomerId=TAble2.CustomerId) 
      INNER JOIN Table3 ON Table2.CustomerId=Table3.CustomerId
WHERE CustomerId = 0015

最后一句是问题......任何想法?

3 个答案:

答案 0 :(得分:6)

错误消息非常清楚,CustomerId子句WHERE中的字段WHERE CustomerId = 0015显示在两个表中。您必须确定要从哪个表中使用它; table1table2?例如:

SELECT Table1.CustomerId, Table1.Address, 
       Table2.CustomerId, Table2.Telephone, 
       Table3.CustomerId, Table3.Notes
FROM (Table1 INNER JOIN Table2 ON Table1.CustomerId=TAble2.CustomerId) 
      INNER JOIN Table3 ON Table2.CustomerId=Table3.CustomerId
WHERE table1.CustomerId = 0015

答案 1 :(得分:5)

您应该在WHERE语句

中指出哪个表是CustomerId
SELECT Table1.CustomerId, Table1.Address, 
       Table2.CustomerId, Table2.Telephone, 
       Table3.CustomerId, Table3.Notes
FROM (Table1 INNER JOIN Table2 ON Table1.CustomerId=TAble2.CustomerId) 
      INNER JOIN Table3 ON Table2.CustomerId=Table3.CustomerId
WHERE Table1.CustomerId = 0015

答案 2 :(得分:1)

您需要初始化您需要客户ID的表。

SELECT Table1.CustomerId, Table1.Address, 
       Table2.CustomerId, Table2.Telephone, 
       Table3.CustomerId, Table3.Notes
FROM (Table1 INNER JOIN Table2 ON Table1.CustomerId=TAble2.CustomerId) 
      INNER JOIN Table3 ON Table2.CustomerId=Table3.CustomerId
WHERE table1.CustomerId = 0015