我对mysql中的SQl查询有疑问。我想选择最近日期时间为id = 1或id = 3的两行
表记录
id | datetime | count
-------------------------------------------------------
1 | 2018-01-02 11:00:00 | 1
2 | 2018-01-02 11:00:00 | 0
3 | 2018-01-02 11:00:00 | 1
1 | 2018-01-02 10:55:00 | 0
2 | 2018-01-02 10:55:00 | 0
3 | 2018-01-02 10:55:00 | 0
1 | 2018-01-02 10:50:00 | 1
2 | 2018-01-02 10:50:00 | 1
3 | 2018-01-02 10:50:00 | 1
我希望我的查询能够重新开始最近的交易:
id | datetime | count
-------------------------------------------------------
1 | 2018-01-02 11:00:00 | 1
3 | 2018-01-02 11:00:00 | 1
有人可以给我任何建议吗?
答案 0 :(得分:0)
尝试联盟
SELECT *
FROM
(SELECT * FROM yourTable WHERE id = 1 ORDER BY datetime DESC LIMIT 1) t1
UNION ALL
(SELECT * FROM yourTable WHERE id = 3 ORDER BY datetime DESC LIMIT 1) t2;
答案 1 :(得分:0)
select id,
max(datetime),
count
from t1 where id in (1,3)
group by id
** t1是你的表
答案 2 :(得分:-1)
select * from tablename where id in (1, 3) order by datetime desc limit 2
答案 3 :(得分:-1)
使用IN,ORDER BY和LIMIT关键字,例如:
SELECT *
FROM MyTable
WHERE id IN (1, 3)
ORDER BY col2 DESC
LIMIT 2
答案 4 :(得分:-1)
使用子查询进行内部联接,该子查询返回ID 1和3的最新事务:
Select only
, the
, columns
, you
, actually
, want
FROM myTable tbl
INNER JOIN
(
SELECT
id,
MAX(datetime) AS most_recent_tran
FROM myTable
WHERE ID in (1,3)
GROUP BY id
) temp
ON
WHATEVER I JUST CALLED MY COLUMNS
tbl.ID = temp.ID and tbl.datetime = temp.datetime