SQL 查询一张卡的最新使用记录
- 1. 问题描述
1. 问题描述
一张卡,有一个底表记录这个卡的基本信息,还有一个使用卡的记录表,记录着,这张卡的使用记录,但我们要获取这张卡的最新使用记录,该如何写SQL呢?
解答:
SELECT
vcr.*
FROM
visitor_card_records vcr
JOIN (
SELECT no,ic_no, MAX(created_at) AS max_created_at
FROM
visitor_card_records
WHERE
state = '使用中'
AND return_at IS NULL
AND ((NO = '1892' AND ic_no = '2630469661'))
GROUP BY no,ic_no
) vcrt ON vcr.NO = vcrt.NO
AND vcr.ic_no = vcrt.ic_no
AND vcr.created_at = vcrt.max_created_at
结果如下
多张卡查询
SELECT
vcr.*
FROM
visitor_card_records vcr
JOIN (
SELECT no,ic_no, MAX(created_at) AS max_created_at
FROM
visitor_card_records
WHERE
state = '使用中'
AND return_at IS NULL
AND ((NO = '1892' AND ic_no = '2630469661') OR (NO = '1890' AND ic_no = '2630957549'))
GROUP BY no,ic_no
) vcrt ON vcr.NO = vcrt.NO
AND vcr.ic_no = vcrt.ic_no
AND vcr.created_at = vcrt.max_created_at
这里使用内连接的方法进行查询
当然如下来写也可以
SELECT id,no,ic_no, visitor_list_id,MAX(created_at) AS max_created_at
FROM
visitor_card_records
WHERE
state = '使用中'
AND return_at IS NULL
AND ((NO = '1892' AND ic_no = '2630469661') OR (NO = '1890' AND ic_no = '2630957549'))
GROUP BY no,ic_no