MySQL获取最近2个工作日的事务

时间:2015-01-24 07:44:12

标签: mysql datediff

我想获取最近2个工作日的交易工作日可能是TODAY & YESTERDAYTODAY & DAY BEFORE YESTERDAYYESTERDAY & DAY BEFORE YESTERDAY

表格结构

id
title
created 

我怎样才能实现这一目标?工作日是指至少1个条目的日子。同一天有多个条目。

要使用此

获取不同的日期
SELECT DISTINCT FROM_UNIXTIME(created, '%Y-%m-%d') as created FROM 
{Table} ORDER BY id DESC LIMIT 2

现在,我如何使用此子查询来获取所有?像这样

SELECT id FROM {Table} WHERE created IN (**sub-query**) 

有可能吗?

另一次尝试,但没有结果

$sql = "SELECT id FROM {Table} WHERE created BETWEEN (SELECT 
DISTINCT FROM_UNIXTIME(created, \'%Y-%m-%d\') FROM {Table} ORDER BY id DESC 
LIMIT 1, 1) AND (SELECT DISTINCT FROM_UNIXTIME(created, \'%Y-%m-%d\') FROM 
{Table} ORDER BY id DESC LIMIT 2, 1) ";

2 个答案:

答案 0 :(得分:2)

请尝试以下查询:

SELECT 
    A.id,
    A.title,
    A.created
FROM 
    {Table} AS A 
    INNER JOIN
    (
        SELECT DISTINCT
            DATE(created) AS WorkingDay
        FROM
            {Table}
        ORDER BY 
            WorkingDay DESC
        LIMIT
            2
    ) AS B
        ON DATE(A.created) = B.WorkingDay 
ORDER BY
    A.created DESC, A.id

请找 NEW SQL Fiddle example,包括时间部分,据我所知,问题很好,会给出预期结果。

查询说明

内部加入的查询:

SELECT DISTINCT
    DATE(created) AS WorkingDay
FROM
    {Table}
ORDER BY 
    WorkingDay DESC
LIMIT
    2

明确选择表{Table} 2个最近日期(WorkingDay),仅从DATE()列值中提取created部分。然后,在条件{Table}上将此结果再次连接到DATE(A.created) = B.WorkingDay后,从{Table}(别名时间AS A)返回的最顶层查询仅返回那些先前发生的那些事务选择了最近的工作日(created日期)。

我希望它有所帮助。

答案 1 :(得分:1)

我认为问题是你没有正确格式化你只需要这样的created

SELECT id FROM {Table} WHERE DATE_FORMAT(created,'%Y-%m-%d') IN (**your subquery here**)  

这应该有效。快乐的编码!