我在围绕嵌套的“select max(date)”样式语句的逻辑/语法方面遇到了困难。让我试着解释一下。我有三个表,我的声明是从中提取数据:
表#1(table1_companies) [id,companyname,industry]
表#2 :( table2_companydata) [id,companyname,data,date_added]
表#3 :( table3_watchlist) [id,companyname,usernane]
我试图执行的声明采用表3中的公司名称,INNER加入表1中的“行业”,然后INNER加入表2中的最新公司信息(基于最后日期)。表2每个公司可以有很多行,我只需要根据添加的最新日期最后一行。我当前(简化)声明没有尝试获取最后一个日期是:
SELECT
table1_companies.industry,
table2_companydata.data,
table3_watchlist.*
FROM
table3_watchlist
INNER JOIN table1_companies ON table1_companies.companyname = table3_watchlist.companyname INNER JOIN table2_companydata ON table2_companydata.companyname = table3_watchlist.companyname WHERE username='username'");
我想我需要在第二个INNER JOIN中插入一个“SELECT max(date_added)FROM table2_companydata”。但我对逻辑或语法都没有成功。可以开导我吗?
答案 0 :(得分:0)
Do the join
s and then select the last record. Here is one method using a where
clause for the logic:
SELECT c.industry, cd.data, w.*
FROM table3_watchlist w INNER JOIN
table1_companies c
ON c.companyname = w.companyname INNER JOIN
table2_companydata cd
ON cd.companyname = w.companyname
WHERE username = 'username' AND
cd.date_added = (select max(cd2.date_added)
from table2_companydata cd2
where cd2.companyname = cd.companyname
);