找到相同的表行

时间:2012-11-28 08:18:13

标签: php mysql sql

在买表中。当客户购买同一本书1行添加到表。因此,当在购买页面中看到购买清单时,就像这样:

buy1 price1 downloadlink1
buy1 price1 downloadlink1
buy1 price1 downloadlink1
buy2 price2 downloadlink2
buy2 price2 downloadlink2
buy2 price2 downloadlink2

但我希望在同一行价格和downloadlink删除,只有第一行显示此值 像这样:

buy1 price1 downloadlink1
buy1 
buy1 
buy2 price2 downloadlink2
buy2 
buy2 

我怎样才能使用sql查询???

3 个答案:

答案 0 :(得分:1)

如果它是MS SQL服务器,我建议使用row_number over() 但在你的情况下,我可以建议尝试这个(我想你的表中有一些id)

select
    A.sub,
    case when A.frst = 1 then A.user else null end as user,
    case when A.frst = 1 then A.versionid else null end as versionid,
    case when A.frst = 1 then A.hard else null end as hard,
    case when A.frst = 1 then A.active else null end as active,
    case when A.frst = 1 then A.res else null end as res
from
(
    select
        *,
        case
            when exists
            (
                select * 
                from buy as tt
                where
                    tt.sub = t.sub and tt.res = t.res and
                    tt.user = t.user and tt.versionid = t.versionid and
                    tt.hard = t.hard and tt.active = t.active and
                    tt.id < t.id
            ) then 0
            else 1
        end as frst
    from buy as t
) as A
order by A.sub, A.frst desc

SQL FIDDLE

答案 1 :(得分:0)

在执行下载链接时在SQL查询中使用distinct

答案 2 :(得分:0)

  

如果该用户未添加该特定项目,则向表中添加行   进入表格

     

如果该项已经存在(使用item id和userid检查)更新   表