简体   繁体   English

MySQL错误1054未知列

[英]MySQL error 1054 unknown column

I have 2 tables. 我有2张桌子。

  1. t_problem t_problem
  2. t_riesenia t_riesenia

In t_problem I have primary key id . 在t_problem中,我有主键id
In t_riesenia I have foreign key ProblemID . 在t_riesenia中,我具有外键ProblemID At least I think I have. 至少我认为我有。
I want to select all fields from table t_problem where there is a solution in t_riesenia (there is a ProblemID in t_riesenia equal to id in t_problem ) 我想选择表中的所有领域t_problem那里是在溶液t_riesenia (有一个ProblemIDt_riesenia等于idt_problem

When trying to execute SQL statement : 尝试执行SQL语句时:

SELECT * FROM `t_problem` where `t_problem`.`id`=`t_riesenia`.`ProblemID`  

I get an error : 我得到一个错误:

Error Code: 1054. Unknown column 't_riesenia.ProblemID' in 'where clause' 错误代码:1054。“ where子句”中的未知列“ t_riesenia.ProblemID”

Why? 为什么? See screenshots from MySQL workbench below. 请参见下面的MySQL工作台截图。

t_problem t_problem t_problem

t_riesenia t_riesenia t_riesenia

t_riesenia Foreign key t_riesenia外键
t_riesenia外键

You should be using an explicit join : 您应该使用显式join

SELECT p.*
FROM t_problem p JOIN
     t_riesenia r
      ON p.id = r.ProblemID;  

It is also possible that you intend an IN : 您也可能打算使用IN

SELECT p.*
FROM t_problem p
WHERE p.id IN (SELECT r.ProblemID FROM t_riesenia r);

The difference between the two is how duplicates are handled in t_riesenia . 两者之间的区别在于在t_riesenia如何处理重复t_riesenia The first returns duplicate rows. 第一个返回重复的行。 The second does not. 第二个没有。

That column may exist somewhere in your database , but it doesn't exist in your query . 该列可能存在于数据库中的某处 ,但在查询中不存在。 You query specifies only one table: 您查询仅指定一个表:

SELECT * FROM `t_problem` where `t_problem`.`id`=`t_riesenia`.`ProblemID`

Note the FROM clause has only a single table. 注意FROM子句只有一个表。 You can see it a little more clearly if you structure it explicitly: 如果您明确地构建它,则可以更清楚地看到它:

SELECT
    *
FROM
    `t_problem`
WHERE
    `t_problem`.`id`=`t_riesenia`.`ProblemID`

The only known table in this query is t_problem . 此查询中唯一已知的表是t_problem In order to add more tables, they need to be added to the FROM clause. 为了添加更多表,需要将它们添加到FROM子句中。 Something like this, for example: 这样的事情,例如:

SELECT
    `t_problem`.*
FROM
    `t_problem`
    INNER JOIN `t_riesenia` ON `t_problem`.`id` = `t_riesenia`.`ProblemID`

(Note that in this case the WHERE clause isn't really needed, since that comparison is going to be true for every joined record.) (请注意,在这种情况下,实际上不需要WHERE子句,因为对于每个连接的记录来说,这种比较都是正确的。)

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

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