使用mysql在某些条件下删除行

时间:2012-05-24 07:51:42

标签: php mysql sql

如果满足某些条件,我希望在表(如下所示)获取新插入时自动删除行。

当:

  • 有些行引用相同的'field'并且具有相同的'user_id'
  • 他们的'字段','显示'和'搜索'列是相同的

简单地说,当行变为重复(“group_id”列除外)时,应删除非null“group_id”,否则应更新或插入行。

有没有办法在mysql中设置它(以“ON DUPLICATE 做东西”的精神结合独特的键等),或者我必须在php中明确检查它(多个查询)?

其他信息: 对于每个可能的“字段”,应该总是有一行NULL'group_id'(有一个有限的集合,在别处定义)。另一方面,可能没有一个非null'group_id'。

CREATE TABLE `Views` (
`user_id` SMALLINT(5) UNSIGNED NOT NULL,
`db` ENUM('db_a','db_b') NOT NULL COLLATE 'utf8_swedish_ci',
`field` VARCHAR(40) NOT NULL COLLATE 'utf8_swedish_ci',
`display` TINYINT(1) UNSIGNED NOT NULL,
`search` TINYINT(1) UNSIGNED NOT NULL,
`group_id` SMALLINT(6) UNSIGNED NULL DEFAULT NULL,
UNIQUE INDEX `user_id` (`field`, `db`, `user_id`),
INDEX `Views_ibfk_1` (`user_id`),
INDEX `group_id` (`group_id`),
CONSTRAINT `Views_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `User` (`id`) ON
UPDATE CASCADE ON DELETE CASCADE
)
COLLATE='utf8_swedish_ci'
ENGINE=InnoDB;

3 个答案:

答案 0 :(得分:2)

我认为你需要修改你的逻辑。仅插入一行来删除另一行是没有意义的。为什么不直接将重复行中的Group_ID字段更新为插入的内容?以下是我将如何进行的粗略概念。

N.b。我还没有完成使用MySQL的工作,并且无法在SQLFiddle上运行以下内容,但根据MySQL docs,我无法解决原因。或许更精通MySQL的人可以纠正我?

SET @User_ID = 1;
SET @db = 'db_a';
SET @Field = 'Field';
SET @Display = 1;
SET @Search = 1;
SET @Group_ID = 1;

IF EXISTS
    (   SELECT  1
        FROM    Views
        WHERE   User_ID = @User_ID
        AND     DB = @DB
        AND     Field = @Field
        AND     Group_ID IS NOT NULL
    ) 
    THEN
        UPDATE  Views
        SET     Group_ID = @Group_ID,
                Display = @Display,
                Search = @Search
        WHERE   User_ID = @User_ID
        AND     DB = @DB
        AND     Field = @Field
        AND     Group_ID IS NOT NULL
ELSE
        INSERT INTO Views (User_ID, DB, Field, Display, Search, Group_ID)
        VALUES (@User_ID, @DB, @Field, @Display, @Search, @Group_ID)
END IF;

或者(以及我的首选解决方案),在表中添加一个Timestamp字段并创建一个视图,如下所示:

SELECT  v.User_ID, v.DB, v.Field, v.Display, v.Search, v.Group_ID
FROM    Views v
        INNER JOIN
        (   SELECT  User_ID, DB, Field, MAX(CreatedDate) AS CreatedDate
            FROM    Views
            WHERE   Group_ID IS NOT NULL
            GROUP BY User_ID, DB, Field
        ) MaxView
            ON MaxView.User_ID = v.User_ID
            AND MaxView.DB = v.DB
            AND MaxView.Field = v.Field
            AND MaxView.CreatedDate = v.CreatedDate
WHERE    v.Group_ID IS NOT NULL
UNION ALL
SELECT  v.User_ID, v.DB, v.Field, v.Display, v.Search, v.Group_ID
FROM    Views v
WHERE   v.Group_ID IS NULL

这样您就可以正确跟踪数据更改,而不会影响查看唯一记录的必要性。

答案 1 :(得分:0)

从其中group_id!='NUll'

的视图中删除group_id

答案 2 :(得分:0)

你的问题不是很好理解,所以我不确定这是你想要的:

DELETE FROM Views WHERE # delete from the table views
  group_id IS NOT NULL AND  # first condition delete only rows with not null group_id
  (SELECT count(*) as tot FROM Views GROUP BY group_id) = 1 # second condition count the difference in group id

如果这不是您想要的,请更新您的问题并提供更多详细信息......