我有一个jiaoyi 表,有以下字段:
id          (自增数字,主键)
buyer       (顾客姓名)
price       (价格)
discount    (折扣)
updatetime  (本条数据插入时间)
数据库里面已有很多数据,由于数据是从网络采集的,会有很多重复的数据,所以我想根据
buyer、price、discount 这三个字段来判断待插入的数据(A记录A)是否与数据库已有的数据(B记录)重复。
当 A记录 的这三个字段的内容与 B记录 同时都相同的时候,则不插入,否则插入。
 
注:id 与 updatetime 这两个字段不作为判断条件。我的语句是select 'buyer1','10','8','2013-09-19' from dual where not exists(select buyer,price,discount,updatetime from jiaoyi where buyer='buyer1')但是好像不对啊,请问大伙应该怎么样写呢?  数据库是mysql,开发语言是c#。
谢谢。
mysqlsql

解决方案 »

  1.   

    select count(*) as num, id from table groupby buyer, price, discount where num > 1
      

  2.   


    我把这个语句复制到mysql里运行,提示出错啊:[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'buyer, price, discount where num > 1' at line 1咋办?  版主可以写个完整点的吗?  就是包括插入语句的。
    谢谢·~
      

  3.   

    select *,count(*) as count from tb1 group by buyer,price,discount having count>=1;
    你把人家的语名复制,不用改表名dual 啊???group by 没分开??
    自已研究吧.
    count的值为记录的数,2即是有两条 price discount buyer部分字段相同的记录....
    3 有三条..................
      

  4.   

    sql 执行语句顺序如下.....
    (8)SELECT (9)DISTINCT  (11)<Top Num> <select list>
    (1)FROM [left_table]
    (3)<join_type> JOIN <right_table>
    (2)        ON <join_condition>
    (4)WHERE <where_condition>
    (5)GROUP BY <group_by_list>
    (6)WITH <CUBE | RollUP>
    (7)HAVING <having_condition>
    (10)ORDER BY <order_by_list>
    因为 group by 之后才有 num 应用having语句
    不知我这个做网管的有没有想,望版主指点下小弟
      

  5.   

    insert into dealdetail(buyer,price,amount,payday,paytime,model,itemid,sellerid,checkedtime) values ('buyername','10','13','2013-09-19','23:28:16','袜子','213666591','5752739','2013-09-20 11:35:26') where exists (select *,count(*) as count from dealdetail group by buyer,price having count=0)这么写不对啊~~
      

  6.   

    终于解决了
    总结一下,有几个方法:方法一:
    一句sql解决insert into 表名(字段1,字段2,字段3,字段n)
    select
    '张三','1','180','2013-09-19','20:23:53','袜子'
    from 表名 a
    where not exists(select 1 from 表名 b where b.判断条件字段1='张三' and b.判断条件字段2='1' and 判断条件字段3='2013-09-13' and 判断条件字段n='23531172612')方法2:使用INSERT INTO… ON DUPLICATE KEY UPDATE
    链接:
    http://blog.zol.com.cn/2299/article_2298921.html
    http://blog.lyphp.com/archives/527
    方法3:使用符合主键,多个判断条件字段组合成一个复合主键
    链接:
    http://www.jb51.net/article/21382.htm方法4:建唯一索引  用ignore into插入数据方法5:使用存储过程
    链接
    http://bbs.csdn.net/topics/390316341
    ---------
    扩展讨论:
    当数据达到上百万条的时候,以上几种方法,哪个方法的性能最佳?
      

  7.   

    SELECT COUNT(*) AS COUNT,ID,UPDATETIME GROUP BY BUYER,PRICE,DISCOUNT HAVINT COUNT(COUNT) > 1 ORDER BY COUNT DESC