我有两张桌子:
表1:
表2:
我需要找到t1的行数,这样,对于id为t1且匹配t2的id的所有行,选择最大日期为t2的行。
最终计数应仅包括满足最大日期t2的行>从现在起30天。
尝试查询:
SELECT COUNT(*)
FROM t1
INNER JOIN t2
ON t2.id = (SELECT id FROM t2 WHERE id = t1.id ORDER BY t2.date DESC LIMIT 1);
SELECT COUNT(*)
FROM t2
INNER JOIN t1 ON t1.id=t2.id
GROUP BY t1.id, t2.date;
注意:我所尝试的查询并不在最终查询的位置附近,我知道。我尝试将问题分解为中间部分,例如尝试使用t2的匹配id获取t1的所有行,然后我尝试仅获取最新的等等。
我无法考虑从第一个表中获取行,但是有条件地将id与第二个表匹配。我无法用SQL来思考。
答案 0 :(得分:1)
您可以使用DATE_ADD()
功能在当前日期添加天数,通过NOW()
函数获取天数:
select count(table1.id), max(table2.date) from table1
INNER JOIN table2 ON table1.id = table2.id
group by table2.date
having DATE(table2.date) > DATE_ADD(NOW(), INTERVAL 30 DAY)
答案 1 :(得分:1)
@WebServlet("/profile")
public class Profile extends HttpServlet {
// Don't use member variables on Servlets - they get reused for all users!
// private String login;
// private HttpSession httpSession;
// private User user;
// private Role role;
public static Logger LOGGER = LogManager.getLogger(Profile.class.getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
HttpSession httpSession = req.getSession();
try (PrintWriter out = resp.getWriter()) {
if (httpSession.getAttribute("userLoggedIn") == null) {
out.println("<title>Login Page</title>");
out.println("<p><a href=\"index\">Please follow the link to login</a></p>");
}
else {
User user = httpSession.getAttribute("userLoggedIn");
Role role = httpSession.getAttribute("userRole");
out.println("<title>Profile page</title>");
out.println("user id = " + user.getUserId());
out.println("login = " + user.getLogin());
out.println("password = " + user.getPassword());
out.println("role = " + role.getRoleName());
out.println("<form action=\"logout\" method=\"get\"/>" +
"<input type=\"submit\" value=\"Logout\"/>" +
"</form>");
if("true".equals(httpSession.getAttribute("isAdmin")) {
httpSession.setAttribute("isAdmin", true);
out.println("<a href=\"admin\">Go to admin page</a>");
}
}
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String login = req.getParameter("login");
User user = new ImplUserDAO().findByLogin(login);
HttpSession httpSession = req.getSession();
try (PrintWriter out = resp.getWriter()) {
if (user != null && user.getPassword().equals(req.getParameter("pass"))) {
Role role = new ImplRoleDAO().findById(user.getRoleId());
httpSession.setAttribute("userLoggedIn", user);
httpSession.setAttribute("userRole", role);
if (role.getRoleName().equals("admin")) {
httpSession.setAttribute("isAdmin", true);
}
// Now refer to display part.
goGet(req, resp);
} else {
out.println("Wrong login or password");
out.println("<a href=\"index\">Please follow the link to login</a>");
}
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
}