自我比较事务表以查找值

时间:2016-08-04 21:11:23

标签: mysql string-comparison self-join

我有一个包含以下字段的mysql表

Transaction_idtoy_idtoy_nameQuantity_soldDate_sold

我想回答的问题是:今天卖的是什么玩具昨天没卖。我明白这是非常模糊的,所以请随意做出任何需要做的假设,以帮助把它写下来,谢谢你!

3 个答案:

答案 0 :(得分:0)

一种方法使用带有having子句的聚合:

select toy_id
from t
where date_sold >= date_sub(curdate(), interval 1 day)
group by toy_id
having date(min(date_sold)) = curdate();

where子句将数据限制为过去两天。如果最低日期是今天,那么昨天没有玩具出售。

答案 1 :(得分:0)

您可以使用not exists运算符查找昨天未售出的玩具。 E.g:

SELECT toy_id, toy_name
FROM   transactions today
WHERE  date_sold = CURRENT_DATE()
       AND NOT EXISTS (SELECT *
                       FROM   transactions yesterday
                       WHERE  today.toy_id = yesterday.toy_id AND
                              yesterday.date_sold = 
                              today.date_solde - INTERVAL 1 DAY);

答案 2 :(得分:0)

您可以使用not in和subselect

  Select Transaction_id, toy_id, toy_name, Quantity_sold, Date_sold
  from my_table  
  where to_id not in (
    select T toy_id 
    from my_table  
    where Date_sold = date(date_sub(now(), INTERVAL 1 day))
  );