选择最近一天的行

时间:2017-02-22 22:51:45

标签: mysql sql database join heidisql

我正在尝试从数据库中的每个用户(用户名)获得最近一天(review_date)写的评论(标题)

My code is :

select tb1.*, tb2.* from 
(select username, via_mobile as pc, max(review_date) as pcdate from tripadvisor where username != "" and via_mobile='false' group by username) tb1
join 
(select username, via_mobile as mobile, max(review_date) as mobile from tripadvisor whereusername != "" and via_mobile='true' group by username) tb2
on tb1.username = tb2.username;

问题是我无法在正确的日期获得正确的评论。 例如:

username; review_date; title 
Alan; 2012-12-18 ;"If..."

但它应显示Alan; 2012-12-18; "Nice hotel"

你能帮我解决一下代码吗?

3 个答案:

答案 0 :(得分:1)

您的问题有点不清楚,但如果我理解正确,您正在查找具有最高日期的每个完整行,明确选择/按用户名分组?这应该给你:

SELECT
  username,
  review_date,
  title
FROM
  tripadvisor AS ta
  INNER JOIN (
    SELECT
      username,
      max(review_date) AS review_date
    FROM
      tripadvisor
    GROUP BY
      username
  ) AS max_table
    ON ta.username = max_table.username
      AND ta.review_date = max_table.review_date;
WHERE
  username != ''
  -- any extra where clauses go here

请参阅:How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

答案 1 :(得分:1)

如果目标是返回"移动"的最新评论标题。对于" pc",我做这样的事情:

specialIndexes.Add(longString.IndexOf(c));

如果用户只有"移动"评论,没有" pc"评论,这个查询将返回一行,但是" pc"列。同样,查询将为" mobile"返回NULL值。仅具有" pc"的用户的列评论

可以轻松地将查询更改为仅返回具有" mobile"的用户的行。和" pc"评论,使用INNER JOIN更接近原文。

如果目标更简单,只需返回最近的评论......

SELECT q.username
     , MAX(q.pc_date)     AS pc_date
     , MAX(p.title)       AS pc_title
     , MAX(q.mobile_date) AS mobile_date
     , MAX(r.title)       AS mobile_title
  FROM ( SELECT t.username
              , MAX(IF(t.via_mobile='false',t.review_date,NULL) AS pc_date
              , MAX(IF(t.via_mobile='true',t.review_date,NULL) AS mobile_date
           FROM tripadvisor t
          WHERE t.username <> ''
            AND t.via_mobile IN ('true','false')
          GROUP
             BY t.username
       ) q
  LEFT
  JOIN tripadvisor p
    ON p.username    = q.username
   AND p.review_date = q.pc_date
   AND p.via_mobile  = 'false'
  LEFT
  JOIN tripadvisor r
    ON r.username    = q.username
   AND r.review_date = q.mobile_date
   AND r.via_mobile  = 'true'
 GROUP
    BY q.username

SELECT r.username , r.review_date , MAX(r.title) AS title , MAX(r.via_mobile) AS via_mobile FROM ( SELECT t.username , MAX(t.review_date) AS max_review_date FROM tripadvisor t WHERE t.username <> '' AND t.via_mobile IN ('true','false') GROUP BY t.username ) q JOIN tripadvisor r ON r.username = q.username AND r.review_date = q.max_review_date AND r.via_mobile IN ('true','false') GROUP BY r.username , r.review_date 包含多个具有相同(最新)username的行时,此查询的结果有些不确定。这可以保证返回单行,但review_datetitle可能不会来自同一行。

答案 2 :(得分:0)

您的问题可以表示为存在测试:显示审核日期与该用户的最新审核日期相匹配的行。

在相关子查询中使用EXISTS测试存在性:

SELECT * FROM tripadvisor as T
where exists ( 
    select 1 from tripadvisor
    where username = T.username
    group by username
    having MAX(review_date) = T.review_date
);