简体   繁体   中英

Select data from another table with where clause

What's wrong with this query, im selecting data from 3 different tables here. First title of exam from "class_exams" table , second selecting sum of total marks from "results" table. Query works fine without where clause.

SELECT id, exam_date , (
SELECT title
FROM class_exams
WHERE result_heads.exam_id = class_exams.id
) AS exam_title, (
SELECT sum( marks )
FROM results
WHERE result_heads.id = results.head_id
) AS obt_marks

FROM `result_heads` WHERE exam_title = 'test';

Error comes

Unknown column 'exam_title' in 'where clause'

Consider using Join

If I understand the table schema , it should be like this :

SELECT result_heads.id, result_heads.exam_date , sum( results.marks )AS obt_marks
FROM results JOIN result_heads
     ON results.exam_id = result_heads.id
GROUP BY result_heads.id, result_heads.exam_date

我认为您需要在Clouse的位置添加表的名称

WHERE `tbl_name`.`exam_title = 'test';

I know this is an old post, but I like to fill the answers where old posts end to prevent dead end posting. It looks like the table name is not being called out in the From clause

See this link http://www.techonthenet.com/mysql/where.php and look at the example - Joining Tables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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