如何在mysql中比较同一个表

时间:2013-09-26 09:54:36

标签: mysql

这是一个mysql问题,我甚至不知道它是否可行,但正如你在下面看到的,我有2个表。他们基本上只是做了同样的差异。一个支付= 1,另一个支付= 0

所以我的头疼是,如果表2中 cardid 价格 title 精确,如表1所示,其中包括paid = 1,不得在表#2中显示。哦,只有在创建匹配时才会进行比较,+ - 5分钟就可以了。

sql语句1

SELECT t.cardid, ct.title, t.transactionid, FROM_UNIXTIME(t.created),t.priceafterdiscount, t.paid 
FROM transactions as t
left join exp_channel_titles ct on t.restaurant_id = ct.entry_id
where t.paid = 0 
and t.transactiontime > '2013-09-23' and 
t.phoneid != '123456789012345' and 
t.cardid != '88888888' and 
t.restaurant_id NOT in (47505) 
ORDER BY t.created DESC;

我的表格1的输出。

Card_ID     Title               Trans_ID Created              price   Paid
10017039    Café Cici           15887   2013-09-26 11:04:49  75     0
10017039    Café Cici           15885   2013-09-26 11:03:08  100    0
10017039    Café Cici           15884   2013-09-26 11:02:33  15000  0
10166152    Viet-Nam Nam        15870   2013-09-25 20:51:44  28800  0
10030773    Restaurant Shezan   15866   2013-09-25 20:10:35  38175  0
10030773    Restaurant Shezan   15865   2013-09-25 20:09:41  50900  0
10030773    Restaurant Shezan   15864   2013-09-25 20:08:13  38175  0

sql语句2

SELECT t.cardid, ct.title, t.transactionid, FROM_UNIXTIME(t.created), t.priceafterdiscount, t.paid
FROM transactions as t
left join exp_channel_titles ct on t.restaurant_id = ct.entry_id
where t.paid = 1
and t.transactiontime > '2013-09-23' and 
t.phoneid != '123456789012345' and 
t.cardid != '88888888' and 
t.restaurant_id NOT in (47505) 
ORDER BY t.created DESC

我的表格2的输出。

Card_ID     Title               Trans_ID Created              price   Paid
10171120    Hjørnet             15889   2013-09-26 11:18:47  6750    1
10017039    Café Cici           15888   2013-09-26 11:06:24  75      1
10017039    Café Cici           15886   2013-09-26 11:04:14  75      1
10129289    Café ZugarBaby      15876   2013-09-25 21:44:34  15000   1
10082903    Café Katz           15862   2013-09-25 19:40:26  19040   1
10064767    Restaurant Fønix    15857   2013-09-25 17:58:53  14250   1

1 个答案:

答案 0 :(得分:0)

从表1中选择*,其中您的条件中的行不在表2中:

select * from 
table1 
left join table2 
on table1.cardid=table2.cardid 
and table1.price=table2.price 
and table1.title=table2.title and 
timestampdiff(minute,table1.created, table2.created) between -5 and 5

where table2.cardid is null

或者,您可以将所有两个查询联合起来,按卡片组,价格,标题分组,并添加具有count(*)= 1和paid = 0的条件,但它不适用于5分钟的时间戳条件