加入两个MySQL查询,其中包含条件和最新时间​​戳

时间:2018-04-11 10:16:00

标签: php mysql

首先查询选定的机构,其次是获得该机构的最新评论。

首先查询:

SELECT 
    instituteId, 
    instituteName, 
    description 
FROM institutions 
WHERE instituteId IN ('1','2','3')";

第二次查询:

SELECT 
    name,
    review, 
    timestamp 
FROM reviews 
WHERE instituteId='1' 
ORDER BY timestamp DESC 
LIMIT 1; 

4 个答案:

答案 0 :(得分:1)

SELECT i.instituteId, 
       i.instituteName, 
       i.description ,
       r.name,
       r.review, 
       r.timestamp
FROM institutions i
INNER JOIN review r
ON i.instituteid = r.instituteId
INNER JOIN (SELECT instituteId,
                   MAX(timestamp) as timestamp
            FROM reviews
            GROUP BY instituteId 
            ) r1
ON r.instituteid = r1.instituteId 
AND r.timestamp = r1.timestamp
WHERE instituteId IN ('1','2','3')

答案 1 :(得分:1)

有很多方法可以做到这一点。但是下面这个给了我在大型数据集中的最佳性能。是的,不要忘记索引列。

//this is just a pseudocode
//df is a master data frame
df1 = df.select(some columns)
df2 = df.select(some columns)
df3 = df.select(some columns)
df4 = df.select(some columns)

df1.write(dir1)
df2.write(dir2)
df3.write(dir3)
df4.write(dir4)

答案 2 :(得分:0)

select i.instituteId, i.instituteName, i.description,
r.name,r.review, r.timestamp
from institutions i inner join reviews  r on i.instituteId=r.instituteId
WHERE instituteId IN ('1','2','3') 
ORDER BY timestamp DESC LIMIT 1

答案 3 :(得分:0)

您可以在一个点上连接两个表,这两个表匹配相同的值和属性

语法: SELECT column_name(s)FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;

解决方案: SELECT i.instituteId,i.instituteName,i.description,v.name,v.review,v.timestamp 从机构i INNER JOIN审查v on i.instituteId = v.instituteId 我在哪里(' 1',' 2',' 3')和v.instituteId = 1 ORDER BY v.timestamp DESC LIMIT 1;