用另一个表加入sql查询

时间:2017-01-02 17:07:00

标签: mysql sql

我使用以下查询来获取最近用户的大多数记录。

SELECT t1.username, t1.value, t1.date
FROM table t1
JOIN (select username, max(date) as maxdate from table
      group by username) t2 on t1.username = t2.username
                           and t1.date = t2.maxdate
WHERE t1.date >= CURDATE()
ORDER BY t1.date DESC

它返回一个包含以下结构的表

------------------------
username | value | date
------------------------

我有另一个结构

的表(t3)
----------------------------
username | category | group
----------------------------

如何获得类似于以下表格结构的结果

-------------------------------------------
username | value | date | category | group
-------------------------------------------

如何加入这些关系?

2 个答案:

答案 0 :(得分:4)

您可以采用以下方式加入:

SELECT t1.username, t1.value, t1.date, t3.category, t3.group
FROM table t1
JOIN (select username, max(date) as maxdate from table
      group by username) t2 on t1.username = t2.username
                           and t1.date = t2.maxdate
JOIN table3 t3 ON t3.username=t1.username
WHERE t1.date >= CURDATE()
ORDER BY t1.date DESC

提示:我不知道mysql,但我认为它在MS SQL中是一样的。

答案 1 :(得分:3)

虽然直接join是最有效和最快捷的方法,但是如果你在t1选择语句中执行诸如max(date)之类的操作(例如在你的t2选择中),你可以构造查询的方式与您在t2选择查询中执行的方式类似:

SELECT maintable.username, maintable.value, maintable.date, secondtable.category, secondtable.group
FROM (
    SELECT t1.username, t1.value, t1.date
    FROM table t1
    JOIN (select username, max(date) as maxdate from table
          group by username) t2 on t1.username = t2.username
                               and t1.date = t2.maxdate
    WHERE t1.date >= CURDATE()
    ORDER BY t1.date DESC
    ) maintable
JOIN table secondtable ON maintable.username = secondtable.username

请注意,如果您没有在内部选择上创建操作,这绝不是最佳选择。