Why does it keep giving me te same errors? - sql

So I wanted to put a sql file in a database (es_extended.sql) and it keeps giving me errors like: duplicate column name name etc. and
SQL error (1050): Table 'items' already exists
I have tried to change the names of columns and all but it keeps giving the same errors.
here is the code:
ALTER TABLE `users`
ADD COLUMN `money` VARCHAR(50) DEFAULT NULL,
ADD COLUMN `name` VARCHAR(50) NULL DEFAULT '' AFTER `money`,
ADD COLUMN `skin` LONGTEXT NULL AFTER `name`,
ADD COLUMN `job` VARCHAR(50) NULL DEFAULT 'unemployed' AFTER `skin`,
ADD COLUMN `job_grade` INT NULL DEFAULT 0 AFTER `job`,
ADD COLUMN `loadout` LONGTEXT NULL AFTER `job_grade`,
ADD COLUMN `position` VARCHAR(36) NULL AFTER `loadout`
;
CREATE TABLE `items` (
`name` varchar(50) NOT NULL,
`label` varchar(50) NOT NULL,
`limit` int(11) NOT NULL DEFAULT '-1',
`rare` int(11) NOT NULL DEFAULT '0',
`can_remove` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`name`)
);
CREATE TABLE `job_grades` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`job_name` varchar(50) DEFAULT NULL,
`grade` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`label` varchar(50) NOT NULL,
`salary` int(11) NOT NULL,
`skin_male` longtext NOT NULL,
`skin_female` longtext NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `job_grades` VALUES (1,'unemployed',0,'unemployed','Unemployed',200,'{}','{}');
CREATE TABLE `jobs` (
`name` varchar(50) NOT NULL,
`label` varchar(50) DEFAULT NULL,
PRIMARY KEY (`name`)
;
INSERT INTO `jobs` VALUES ('unemployed','Unemployed');
CREATE TABLE `user_accounts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(22) NOT NULL,
`name` varchar(50) NOT NULL,
`money` double NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
);
CREATE TABLE `user_inventory` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(22) NOT NULL,
`item` varchar(50) NOT NULL,
`count` int(11) NOT NULL,
PRIMARY KEY (`id`)
);

Sql databases are a way to implement the persistence layer: data that should be kept permanently or at least independently from sessions.
The error you're getting: SQL error (1050): Table 'items' already exists means that you've already created a table with the same name you're using to try and create a new table.
You do not need to recreate the table each time you try to add data to it. The table is persistent as long as you do not DROP (delete) it or the database it belongs to.
If you want to recreate the table (either because you need to change its schema or because you want to start over), you can run the command DROP TABLE items which will delete the table and all data in the table.
After dropping, you can run the CREATE TABLE items... command again.
If you don't want to delete the table, you can just run the INSERT INTO items... command to add data to the existing table.
The SQL Error (xxxx): duplicate column name 'name' error means you are trying to add a column that already exists in the table. If the users table already has a column called name, then you cannot run the command ALTER TABLE users ADD COLUMN 'name'... without an error.
If the column doesn't meet your needs anymore, you can use ALTER TABLE users ALTER COLUMN 'name'... to change the schema for the column.

Related

How to delete a record from database where all fields are the same to another?

I have two only records in a database table and I want to delete only one of them.
The problem is that I don't have any primary key nor unique identifier, so how could I delete one and only one record?
It seems a easy question but I didn't find out how to do it ¿?.
CREATE TABLE `ToDo` (
`id` bigint(20) NOT NULL,
`caption` varchar(255) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`priority` int(11) DEFAULT NULL,
`done` tinyint(1) DEFAULT NULL,
`idUser_c` int(11) DEFAULT NULL,
`idUser_u` int(11) DEFAULT NULL,
`idUser_d` int(11) DEFAULT NULL,
`date_c` datetime DEFAULT NULL,
`date_u` datetime DEFAULT NULL,
`date_d` datetime DEFAULT NULL,
`version` bigint(20) DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `ToDo` (`id`,`caption`,`description`,`priority`,`done`,`idUser_c`,`idUser_u`,`idUser_d`,`date_c`,`date_u`,`date_d`,`version`) VALUES (3,'hello','how are you',2,0,1,1,1,'2018-03-03 13:35:54','2018-03-03 13:35:57','2018-03-03 13:36:00',0);
INSERT INTO `ToDo` (`id`,`caption`,`description`,`priority`,`done`,`idUser_c`,`idUser_u`,`idUser_d`,`date_c`,`date_u`,`date_d`,`version`) VALUES (3,'hello','how are you',2,0,1,1,1,'2018-03-03 13:35:54','2018-03-03 13:35:57','2018-03-03 13:36:00',0);
This addresses the title, which implies potentially more than 2 rows in the table:
CREATE TABLE new LIKE ToDo;
INSERT INTO new
SELECT DISTINCT id, caption, ...
FROM ToDo;
RENAME TABLE ToDo TO old,
new TO ToDo;
DROP TABLE old;
Well, what a good reason for an auto-incremented column! Well, you can add one:
alter table todo add ToDoId int auto_increment primary key;
This also sets the value.
Then you can do:
delete td
from todo td join
todo td1
on td.id = td1.id and td.caption = td1.caption and . . . and
td1.id < td.id;
This assumes that the columns are not NULL.
Alternatively, fix the entire table:
create temporary table temp_todo as
select *
from todo;
truncate table todo;
insert into todo
select distinct *
from todo;
This handles NULL values better than the first version.
Along the way, fix the table to have an auto-incremented primary key, so you can avoid this problem forevermore.
I think I found it myself, I just got stuck for a sec!
DELETE FROM ToDo WHERE ... LIMIT 1;

Only insert in table when it meets certain condition from another table SQL

I have table called Create_Group. I would like to add a constraint that only people with user_type staff can insert in the table Create_group.
CREATE TABLE `User`
(
`user_id` varchar(10) NOT NULL,
`username` varchar(20) NOT NULL,
`user_type` varchar(20) NOT NULL,
CONSTRAINT UC_User UNIQUE (user_id,username)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `User` ADD PRIMARY KEY (`user_id`);
I have tried doing this:
CREATE TABLE `Create_Group`
(
`group_id` varchar(10) NOT NULL,
`user_id` varchar(10) NOT NULL,
`group_creator` varchar(20) NOT NULL,
`group_name` varchar(50) NOT NULL,
CONSTRAINT UC_Group UNIQUE (group_id,group_name)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `Create_Group`
ADD PRIMARY KEY (`group_id`),
ADD KEY (`user_id`);
UPDATE `Create_Group`
SET `group_id`,`user_id`,`group_creator`,`group_name`,`date_created`
WHERE (SELECT user_type
FROM User
WHERE `group_creator`=username) = `Staff`
However the update keeps giving me an error.
Example of input for User:
INSERT INTO `User` (`user_id`, `username`, `user_type`)
VALUES (UUID(), 'TheDoctor', 'Staff'), (UUID(), 'DoctorStrange', 'User');
Example of input for Group_Create:
INSERT INTO `Create_Group` (`group_id`, `user_id`, `group_creator`, `group_name`, `date_created`)
SELECT
UUID(),user_id,'TheDoctor','HeroesUnited', CURRENT_TIMESTAMP()
FROM
User
WHERE
username='TheDoctor'
Thanks in advance!
Whichever SQL database you might be using. This Update seems incorrect, as no value is being assigned to it
Following seems incorrect
UPDATE `Create_Group`
SET `group_id`,`user_id`,`group_creator`,`group_name`,`date_created`
WHERE (SELECT user_type
FROM User
WHERE `group_creator`=username) = `Staff`
Try assigning some value to fields in SET like:
Note this is just example of how to correct the update query:
UPDATE `Create_Group`
SET `group_id` = '1',`user_id` = '2',`group_creator`='3',`group_name`='name',`date_created`='2017-01-01'
WHERE (SELECT user_type
FROM User
WHERE `group_creator`=username) = `Staff`
Also you should take care of the WHERE clause query. If more than 1 records will be returned by subquery
(SELECT user_type FROM User WHERE group_creator=username)
then the update will fail with error
more than one row returned by a subquery used as an expression

Mysql - Error code 1054 Unknown cloumn 'players.p_name' in 'where clause'

Hello,
first of all I want you to show my table I have:
CREATE TABLE `channels` (
`channel_id` int(11) NOT NULL AUTO_INCREMENT,
`channel_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`channel_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
CREATE TABLE `gamepoints` (
`gp_id` int(11) NOT NULL AUTO_INCREMENT,
`gamble` int(11) DEFAULT NULL,
`roulette` int(11) DEFAULT NULL,
`blackjack` int(11) DEFAULT NULL,
`slots` int(11) DEFAULT NULL,
PRIMARY KEY (`gp_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
CREATE TABLE `player_channel` (
`pc_id` int(11) NOT NULL AUTO_INCREMENT,
`players_id` int(11) DEFAULT NULL,
`channel_id` int(11) DEFAULT NULL,
PRIMARY KEY (`pc_id`),
KEY `players_id_idx` (`players_id`),
KEY `channel_id_idx` (`channel_id`),
CONSTRAINT `channel_id` FOREIGN KEY (`channel_id`) REFERENCES `channels` (`channel_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `players_id` FOREIGN KEY (`players_id`) REFERENCES `players` (`players_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
CREATE TABLE `players` (
`players_id` int(11) NOT NULL AUTO_INCREMENT,
`p_name` varchar(45) DEFAULT NULL,
`p_right` varchar(45) DEFAULT NULL,
`gp_id` int(11) DEFAULT NULL,
PRIMARY KEY (`players_id`),
KEY `gp_id_idx` (`gp_id`),
CONSTRAINT `gp_id` FOREIGN KEY (`gp_id`) REFERENCES `gamepoints` (`gp_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
I wanted to this query:
UPDATE gamepoints SET gamble = 1
WHERE gamepoints.gp_id = players.gp_id
AND players.p_name = "test"
AND player_channel.players_id = players.players_id
AND player_channel.channel_id = channels.channel_id
AND channels.channel_name = "test";
But when I do this i get this Error:
Error Code: 1054. Unknown column 'players.p_name' in 'where clause'
I don't know what I am doing wrong, i tryed also after set to add from with all tables, but this works also not.
I would be really happy if someone can help me :)
Thanks in advance
You omitted the table names of all but gamepoints. I would recommend that you use explicit join update syntax, which makes it harder to have this sort of error:
UPDATE gamepoints t1
INNER JOIN players t2
ON t1.gp_id = t2.gp_id
INNER JOIN player_channel t3
ON t3.players_id = t2.players_id
INNER JOIN channels t4
ON t4.channel_id = t3.channel_id
SET t1.gamble = 1
WHERE t2.p_name = 'test' AND
t4.channel_name = 'test';
If you wanted to salvage your current query, then it would start off looking something like this:
UPDATE gamepoints, players, player_channel, channels
SET gamble = 1
WHERE -- a very large number of conditions
One reason implicit joins are frowned upon is that they mix normal restrictions on the result set with join conditions, all in the same WHERE clause. This doesn't happen with the query as I wrote it using explicit joins.

I get "a foreign key constraint fails" error when attempting to join two classes/tables

I have these classes, abbreviated for practical reasons:
class CV {
Date dateCreated
static hasMany=[proposals: Proposal]
}
class Proposal {
String name
Date date_started
static hasMany = [CVs: CV]
static belongsTo = CV
}
Grails creates tables for both these classes, and a third class named "cv_proposals" joining them. So far, so good. I have data in both the CV and the Proposal tables, they both have autoincremented "id" values. All good.
in Oracle MySQL Workbench, I try to manually add values to the joining table to get some dummy data to work with. I get an error message with this trace:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
(cvreg_utv.cv_proposals, CONSTRAINT FK17D946F55677A672 FOREIGN KEY (cv_id) REFERENCES cv (id))
I made sure both the tables had several lines of data in them, and that I could edit both of them separately.
After trying dropping and recreating the table, altering the classes back and forth, I'm kind of convinced that this operation somehow has to be done through a running Grails application. So I write this script in a controller and run it:
def g = CV.get(1)
Proposal proposal = g.addToProposals(new Proposal(
name: "SavingTest",
date_started: new Date())).save()
I still get the same error, though. Is this not the right way to define a proposal that is connected to a certain CV? Am I wrong in using a many-to-many connection here somehow?
Edit: adding the schema-create script for the joining table
delimiter $$
CREATE TABLE `cv_proposals` (
`proposal_id` bigint(20) NOT NULL,
`cv_id` bigint(20) NOT NULL,
PRIMARY KEY (`cv_id`,`proposal_id`),
KEY `FK17D946F55677A672` (`cv_id`),
KEY `FK17D946F5F7217832` (`proposal_id`),
CONSTRAINT `FK17D946F5F7217832` FOREIGN KEY (`proposal_id`) REFERENCES `proposal` (`id`),
CONSTRAINT `FK17D946F55677A672` FOREIGN KEY (`cv_id`) REFERENCES `cv` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
And the CV table:
CREATE TABLE `cv` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`version` bigint(20) NOT NULL,
`user_id` bigint(20) NOT NULL,
`version_name` varchar(255) DEFAULT NULL,
`date_created` datetime NOT NULL,
`last_updated` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `FKC734A9AB992` (`user_id`)
) ENGINE=MyISAM AUTO_INCREMENT=101 DEFAULT CHARSET=latin1$$
And the Proposal table:
CREATE TABLE `proposal` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`version` bigint(20) NOT NULL,
`date_ended` datetime NOT NULL,
`date_started` datetime NOT NULL,
`description` varchar(500) DEFAULT NULL,
`name` varchar(500) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1$$
This is the insert script I tried to run:
INSERT INTO `cvreg_utv`.`cv_proposals` (`proposal_id`, `cv_id`)
VALUES ('1', '1');
You crated the tables manually? It's interesting that cv table is using MyISAM engine and the others uses InnoDB.
I think you want to use InnoDB to all your tables, since this engine is transactional. In my test, I also was unable to create the cv_proposals table until I changed the cv creation:
CREATE TABLE cv (
id bigint(20) NOT NULL AUTO_INCREMENT,
version bigint(20) NOT NULL,
user_id bigint(20) NOT NULL,
version_name varchar(255) DEFAULT NULL,
date_created datetime NOT NULL,
last_updated datetime NOT NULL,
PRIMARY KEY (id),
KEY FKC734A9AB992 (user_id)
) ENGINE=InnoDB AUTO_INCREMENT=101
After that, the insert's worked smoothly.

MySQL: Name primary key in CREATE TABLE statement

How do I set the name of a primary key when creating a table?
For example here I'm trying to create a primary key with the name 'id', but this is invalid SQL. Can you tell me the correct way to do this?
CREATE TABLE IF NOT EXISTS `default_test`
(
`default_test`.`id` SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY `id`,
`default_test`.`name` LONGTEXT NOT NULL
)
Clarification
I'd like to specify the name of the primary key - rather than the default name of "PRIMARY" I'd like it to be called "id" or perhaps "primary_id", so if I were to later run SHOW INDEXES FROM default_test, the Key_name will be something I have specified.
Alternatively and more widely supported:
CREATE TABLE IF NOT EXISTS `default_test` (
`default_test`.`id` SMALLINT NOT NULL AUTO_INCREMENT,
`default_test`.`name` LONGTEXT NOT NULL,
PRIMARY KEY (`id`)
)
UPDATE
Based on the clarification, you could replace the last definition above with the following if you are to specify the index name:
CONSTRAINT `pk_id` PRIMARY KEY (`id`)
http://dev.mysql.com/doc/refman/5.1/en/create-table.html
[...] In MySQL, the name of a PRIMARY KEY is PRIMARY. [...]
CREATE TABLE IF NOT EXISTS `default_test` (
`default_test`.`id` SMALLINT NOT NULL AUTO_INCREMENT,
`default_test`.`name` LONGTEXT NOT NULL,
PRIMARY KEY (`id`)
)
You shouldn't specify the column name when you specify the primary key column name directly inline with the column definition, so:
CREATE TABLE IF NOT EXISTS `default_test` (
`default_test`.`id` SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`default_test`.`name` LONGTEXT NOT NULL
);
Alternativly you could do:
CREATE TABLE IF NOT EXISTS `default_test` (
`default_test`.`id` SMALLINT NOT NULL AUTO_INCREMENT ,
`default_test`.`name` LONGTEXT NOT NULL ,
PRIMARY KEY `default_test_id_pkey` (`id`)
);
You don't have to specify the column name again, because you already specified it as part of the current field definition - just say PRIMARY KEY.
CREATE TABLE IF NOT EXISTS `default_test` (
`id` SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` LONGTEXT NOT NULL
)
Alternatively, you can specify it separately later:
CREATE TABLE IF NOT EXISTS `default_test` (
`id` SMALLINT NOT NULL AUTO_INCREMENT,
`name` LONGTEXT NOT NULL,
PRIMARY KEY(`id`)
)