简体   繁体   中英

SELECT LAST ROW WITH AN INNER JOIN

I have two relational tables [category] and [briefs]. I want to select the last ROW FROM briefs WHERE briefs.category_id = category.category_id;

[Category]
category_id
category_name

[briefs]
brief_id
category_id
brief_file_num
brief_date



 "SELECT brief_file_num,category_id FROM briefs,category 
WHERE briefs.category_id = category.category_id ORDER BY briefs.brief_file_num 
DESC LIMIT 1";

I am receiving the following error: "Column 'category_id' in field list is ambiguous"

Even when both category have the same value. you need to specify what table are you refering too because both have a column with that name

Also use explict JOIN sintaxis, Aaron Bertrand wrote a nice article Bad habits to kick : using old-style JOINs about it.

 SELECT briefs.brief_file_num,
        briefs.category_id    
 FROM briefs
 INNER JOIN category 
    ON briefs.category_id = category.category_id 
 ORDER BY briefs.brief_file_num 
 DESC LIMIT 1"

Both tables have a category_id , which is ambiguous. Use category.category_id instead!

SELECT brief_file_num,category.category_id FROM briefs,category 
WHERE briefs.category_id = category.category_id ORDER BY briefs.brief_file_num 
DESC LIMIT 1

You should explicitally add the tables names for avoid ambiguity

   "SELECT briefs.brief_file_num, briefs.category_id 
     FROM briefs,category 
     WHERE briefs.category_id = category.category_id ORDER BY briefs.brief_file_num 
    DESC LIMIT 1";

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