如何删除列没有在同一个表中重复

时间:2015-11-24 14:23:23

标签: sql sql-server database

我有这个样本数据: -

===============
pageid||SiteID
===============
   61  ||   1 

   62  ||   1 

   63  ||   1

   62  ||   2 

  

这个表引用其他表的页面,其他的pageid是唯一的   表

我需要删除此表和引用表中的数据....但如果记录重复与其他站点ID我不能删除它,当我选择与站点ID所有pageid将删除(我可以删除所有pageid但是我希望在页面表中保留它)

4 个答案:

答案 0 :(得分:1)

DELETE FROM @Page_Site
WHERE siteID=@siteID
AND pageID not 
in(
    SELECT pageID 
    FROM @Page_Site p2
    WHERE p2.siteID!=@siteID
);

我不确定您如何使用查询,因此我将其格式化为参数化查询。否则,您只需将@siteID的两个实例替换为任何给定值。

答案 1 :(得分:1)

使用NOT EXISTS子句来防止删除在不同siteID中使用的pageid

试试这个:

DELETE FROM yourtable
WHERE NOT EXISTS(
    SELECT 'OTHERSITE'
    FROM yourtable T2
    WHERE T2.pageid = yourtable.pageid
    AND T2.siteID <> yourtable.siteID)

答案 2 :(得分:1)

我喜欢SQL Server允许使用deleteupdate的窗口函数的方式。因此,也可以将这些功能用于此目的:

with todelete as (
      select s.*, min(siteId) over (partition by pageid) as mins,
             max(siteId) over (partition by pageid) as maxs
      from sample s
     )
delete from todelete
    where mins = maxs;

答案 3 :(得分:0)

您需要在2个查询中执行此操作。首先删除所有链接ID,然后删除页面本身

{
  "name": "Fast-nunjucks",
  "version": "0.0.1",
  "description": "A simple boilerplate using nunjucks as a template engine",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/willianjusten/Fast-nunjucks.git"
  },
  "keywords": [
    "nunjucks",
    "node",
    "gulp",
    "stylus"
  ],
  "author": "Willian Justen de Vasconcellos",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/willianjusten/Fast-nunjucks/issues"
  },
  "homepage": "https://github.com/willianjusten/Fast-nunjucks",
  "devDependencies": {
    "autoprefixer-stylus": "^0.7.1",
    "browser-sync": "^2.8.2",
    "gulp": "^3.9.0",
    "gulp-cache": "^0.3.0",
    "gulp-concat": "^2.6.0",
    "gulp-if": "^1.2.5",
    "gulp-imagemin": "^2.3.0",
    "gulp-minify-html": "^1.0.4",
    "gulp-nunjucks-html": "^1.2.2",
    "gulp-order": "^1.1.1",
    "gulp-plumber": "^1.0.1",
    "gulp-stylus": "^2.0.6",
    "gulp-uglify": "^1.2.0",
    "gulp-util": "^3.0.6",
    "jeet": "^6.1.2",
    "kouto-swiss": "^0.11.13",
    "minimist": "^1.1.3",
    "rupture": "^0.6.1"
  },
  "dependencies": {
    "gulp-install": "^0.6.0"
  }
}