0

我正在尝试将组名插入到我的数据库中。由于它们是用户组,我只想插入一次,所以如果我不小心再次插入它们,它应该拒绝它,因为它已经存在。我也在使用 PDO 语句。

// groups
$db->query("CREATE TABLE IF NOT EXISTS groups ( ID INT NOT NULL AUTO_INCREMENT, 
                    name VARCHAR(200),
                    primary key (ID)
            )");        

// Fill tables

//Groups
$db = connectDatabase();    
$name = 'Administrator';
$query = $db->prepare("INSERT INTO groups (name) SELECT :name WHERE NOT EXISTS (SELECT * FROM groups WHERE name = :name)");
$query->bindParam(':name', $name);
$query->execute();

$name = 'Moderator';
$query = $db->prepare("INSERT INTO groups (name) SELECT :name WHERE NOT EXISTS (SELECT * FROM groups WHERE name = :name)");
$query->bindParam(':name', $name);
$query->execute();

由于某种原因,它没有向表组添加任何内容。谁能帮我这个?

非常感谢

4

3 回答 3

5

为什么不直接取名UNIQ呢?

$db->query("CREATE TABLE IF NOT EXISTS groups ( ID INT NOT NULL AUTO_INCREMENT, 
                    name VARCHAR(200),
                    primary key (ID),
                    UNIQUE KEY `name` (`name`)
            )");        

然后进行INSERT IGNORE

$db = connectDatabase();    
$name = 'Administrator';
$query = $db->prepare("INSERT IGNORE INTO groups (name) VALUES (:name)");
$query->bindParam(':name', $name);
$query->execute();
于 2013-04-22T11:25:04.923 回答
0

你忘了FROM这里

INSERT INTO groups (name) SELECT :name 
FROM groups WHERE NOT EXISTS 
(SELECT * FROM groups WHERE name = :name)
于 2013-04-22T11:19:25.637 回答
-1

尝试关注

If Not Exists(select * from groups where name=:name)
Begin
insert into groups(name) values (:name)
End
于 2013-04-22T11:20:38.243 回答