modification of the content on a specific column in mysql. better in a single update? - mysql

The name of the card "Rascals" (line 55 of the excel) it will be modified by "Hal Roach's Rascals", and the rerity "Common" it will be "Proletari"
DROP TABLE IF EXISTS Carta;
CREATE TABLE Cards(
id_carta VARCHAR(255),
name VARCHAR(255),
rarity VARCHAR(255),
deck VARCHAR(255),
player VARCHAR(255),
level VARCHAR(255),
PRIMARY KEY(id_carta),
FOREIGN KEY(rarity)REFERENCES Rarity(id_rarity),
FOREIGN KEY(deck)REFERENCES Deck(id_deck),
);
My code is:
UPDATE cards SET cards_name = 'Hal Roachs Rascals' WHERE cards_name = 'Rascals';
UPDATE cards_rarity = 'Proletari' WHERE cards_rarity = 'Common;
My question is if it is correct or it could be do it in a single update?

"when the name of a card is like "RASCALS" I must change that name with "Hal Ro..." and then change only the rarity of this card not all the cards which have "common" rarity"
It is like that:
UPDATE cards SET cards_name = 'Hal Roachs Rascals' AND cards_rarity=’Proletari’ WHERE cards_name = 'Rascals'; ???

Related

Issue with UPDATE in this MySQL Code to modify a song's release year?

The given SQL creates a Song table and inserts three songs.
Write three UPDATE statements to make the following changes:
Change the title from 'One' to 'With Or Without You'.
Change the artist from 'The Righteous Brothers' to 'Aritha Franklin'.
--I know they misspelled Aretha, that's not the problem
Change the release years of all songs after 1990 to 2021.
Run your solution and verify the songs in the result table reflect the changes above.
CREATE TABLE Song (
ID INT,
Title VARCHAR(60),
Artist VARCHAR(60),
ReleaseYear INT,
PRIMARY KEY (ID)
);
INSERT INTO Song VALUES
(100, 'Blinding Lights', 'The Weeknd', 2019),
(200, 'One', 'U2', 1991),
(300, 'You\'ve Lost That Lovin\' Feeling', 'The Righteous Brothers', 1964),
(400, 'Johnny B. Goode', 'Chuck Berry', 1958);
-- Write your UPDATE statements here:
UPDATE Song
SET Title = 'With Or Without You' WHERE ID = 200;
UPDATE Song
SET Artist = 'Aritha Franklin' WHERE ID = 300;
UPDATE Song
SET ReleaseYear = 2021;
SELECT *
FROM Song;
It should be noted that the solution as is, works. I already got credit for this solution.
My issue comes towards the end, The assignment specifically wants songs released after 1990 to be changed to 2021 which would be ID's 100, 200. This solution changed everything to 2021. I tried doing this...
SET ReleaseYear = 2021 WHERE ID = (100, 200);
But It freaks out because there are 2 operands. So then I tried
CREATE TABLE Song (
ID INT,
Title VARCHAR(60),
Artist VARCHAR(60),
ReleaseYear INT,
PRIMARY KEY (ID)
);
INSERT INTO Song VALUES
(100, 'Blinding Lights', 'The Weeknd', 2019),
(200, 'One', 'U2', 1991),
(300, 'You\'ve Lost That Lovin\' Feeling', 'The Righteous Brothers', 1964),
(400, 'Johnny B. Goode', 'Chuck Berry', 1958);
-- Write your UPDATE statements here:
UPDATE Song
SET Title = 'With Or Without You' WHERE ID = 200;
UPDATE Song
SET Artist = 'Aritha Franklin' WHERE ID = 300;
ALTER TABLE Song
ADD CONSTRAINT ReleaseYearCheck CHECK (ReleaseYear >= 1990);
SET ReleaseYear = 2021;
SELECT *
FROM Song;
It fails the constraint check as I would expect. I have no idea how to change it to just specifically modify "Blinding Lights", and "With or Without You" to have a release year of 2021.
I can ONLY add code where it states "--Write your UPDATE statements here:".
Keep in mind the first code block which I already worked out, gives me credit for the question. I believe there is an error in the assignment checker thing, because the first code block changed everything's release year. Per the question, it would seem it only wants to see the ReleaseYear change for Blinding Lights, and With or Without You to 2021.
Given the criteria is above 1990:
UPDATE Song
SET ReleaseYear = 2021
WHERE ReleaseYear >= 1990
This worked for me
CREATE TABLE Song (
ID INT,
Title VARCHAR(60),
Artist VARCHAR(60),
ReleaseYear INT,
PRIMARY KEY (ID)
);
INSERT INTO Song VALUES
(100, 'Blinding Lights', 'The Weeknd', 2019),
(200, 'One', 'U2', 1991),
(300, 'You've Lost That Lovin' Feeling', 'The Righteous Brothers', 1964),
(400, 'Johnny B. Goode', 'Chuck Berry', 1958);
-- Write your UPDATE statements here:
UPDATE Song
SET Title = 'With Or Without You'
WHERE Title = 'One';
UPDATE Song
SET Artist = 'Aretha Franklin'
Where ID = 300;
UPDATE Song
SET ReleaseYear = '2021'
WHERE ReleaseYear >1990;
SELECT *
FROM Song;

SQLAlchmemy — get related objects with reflected tables

I am quite new to sqlalchemy, I guess I am missing just a little piece here.
There is this Database (sql):
create table CEO (
id int not null auto_increment,
name char(255) not null,
primary key(id),
unique(name)
);
create table Company (
id int not null auto_increment,
name char (255) not null,
ceo int not null,
primary key(id),
foreign key(ceo) references CEO(id)
);
That code:
from sqlalchemy import create_engine, Table, Column, Integer, String, ForeignKey
from sqlalchemy.orm import registry, relationship, Session
engine = create_engine(
"mysql+pymysql:xxxxxxxx",
echo=True,
future=True
)
mapper_registry = registry()
Base = mapper_registry.generate_base()
#####################
## MAPPING CLASSES ##
#####################
class CEO(Base):
__table__ = Table('CEO', mapper_registry.metadata, autoload_with=engine)
companies = relationship('Company', lazy="joined")
class Company(Base):
__table__ = Table('Company', mapper_registry.metadata, autoload_with=engine)
##########################
## FINALLY THE QUESTION ##
##########################
with Session(engine, future=True) as session:
for row in session.query(CEO).all():
for company in row.companies:
## Just the id of the Ceo is yielded here
print(company.ceo)
So CEO.companies works as expected, but Company.ceo does not, even though the FOREIGN KEY is defined.
What is a proper setup for the Company Mapper class, such that Company.ceo yields the related object?
I could figure out, that the automatic setup did not work, because the column Company.ceo exists in the Database and represents the ID of a given row. To make everything work, I needed to rename Company.ceo to Company.ceo_id and add the relation manually like so:
CompanyTable = Table('Company', Base.metadata, autoload_with=engine)
class Company(Base):
__table__ = CompanyTable
ceo_id = CompanyTable.c.ceo
ceo = relationship('CEO')
I would like to know if it would be possible to rename the column within the Table(…) call, such that I could get rid of the extra CompanyTable thing.

Preventing duplicate entry in database before inserting value into database

I am trying to check the database to see if the activity Name that I am entering already exists, if it exists I should get an error if it don't it should go ahead and insert values into database, below is the code I am trying but it isn't working properly btw the prevention of duplicates is already working cause of the UNIQUE KEY i give to activity Name but I also want an alert to let the users know that the activity name already exists.
function insertQueryDB(tx) {
var myDB = window.openDatabase("test", "1.0", "Test DB", 1000000);
tx.executeSql('CREATE TABLE IF NOT EXISTS dataEntryTb (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, activityName TEXT NOT NULL UNIQUE, location TEXT NOT NULL, time NOT NULL, date NOT NULL, reporter NOT NULL)');
var an = document.forms["myForm"]["activityName"].value;
var l = document.forms["myForm"]["location"].value;
var t = document.forms["myForm"]["time"].value;
var d = document.forms["myForm"]["date"].value;
var r = document.forms["myForm"]["reporter"].value;
if('COUNT activityName FROM dataEntryTb WHERE EXISTS activityName = "'+an+'" '){
navigator.notification.alert("activityName already Exists");
}
var query = 'INSERT INTO dataEntryTb ( activityName, location, time, date, reporter) VALUES ( "'+an+'", "'+l+'", "'+t+'", "'+d+'", "'+r+'")';
tx.executeSql(query,[]);
navigator.notification.alert("Retrieved the following: Activity Name="+an+" and Location="+l);
}
I think all you need to do is establish an unique key on activityName...
alter table dataEntryTb add unique key (activityName);

MySQL: ERROR: failed to open file error2

Here are my steps:
1. use bank(my database);
2. SOURCE d:\Nitro\testing\SQL\Books_mysql\Cookbook\recipes\tables\cow.sql
When I tried to source for a particular .sql file, namely 'cow.sql', the following error is displayed:
ERROR:
Failed to open file 'd:\Nitro\testing\SQL\Books_mysql\Cookbook\recipes\tables\cow.sql', error:2
content of "cow.sql":
# Tables for online contruct-a-cow ordering scenario
DROP TABLE IF EXISTS cow_order;
## _CREATE_COW_ORDER_TABLE_
CREATE TABLE cow_order
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
# cow color, figurine size, and accessory items
color VARCHAR(20),
size ENUM('small','medium','large') DEFAULT 'medium',
accessories SET('cow bell','horns','nose ring','tail ribbon')
DEFAULT 'cow bell,horns',
# customer name, street, city, and state (abbreviation)
cust_name VARCHAR(40),
cust_street VARCHAR(40),
cust_city VARCHAR(40),
cust_state CHAR(2),
PRIMARY KEY (id)
);
## _CREATE_COW_ORDER_TABLE_
# Add some orders to the table
INSERT INTO cow_order (color, size, accessories,
cust_name, cust_street, cust_city, cust_state)
VALUES
('Black & White','large','cow bell,nose ring',
'Farmer Brown','123 Elm St.','Bald Knob','AR');
SELECT * FROM cow_order\G
DROP TABLE IF EXISTS cow_color;
## _CREATE_COW_COLOR_TABLE_
CREATE TABLE cow_color (color CHAR(20));
## _CREATE_COW_COLOR_TABLE_
INSERT INTO cow_color (color)
VALUES
('Black'),
('Brown'),
('Cream'),
('Black & White'),
('Red & White'),
('Red'),
('See-Through');
SELECT * FROM cow_color;
You seem to be on Windows. Here you need to use forward slashes!
USE bank;
SOURCE D:/Nitro/testing/SQL/Books_mysql/Cookbook/recipes/tables/cow.sql;
Alternatively, you can use escaped back slashes:
SOURCE D:\\Nitro\\testing\\SQL\\Books_mysql\\Cookbook\\recipes\\tables\\cow.sql;
On Windows, use forward slash (/) in in path, and provide full path.
For example:
source C:/wamp64/bin/mariadb/mariadb10.4.10/bin/goblissl_oc.sql

Storing Percentages in MySQL

I'm trying to store a percentage value in a MySQL database but when ever I try and set the value of the percentage column to 100%, I get an "Out of range value" error message.
I am currently using a DECIMAL(5,2) type and I need to be able to store values from 0% up to 100% (with 2dp when the value isn't an integer) ( the values are being calculated in a php script).
All values are fine apart from 100% which triggers the error.
Am I misunderstanding something or is there something else I am missing?
EDIT: The table was created using the following sql
CREATE TABLE overviewtemplate
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(32),
numberOfTests INT NOT NULL DEFAULT 0,
description VARCHAR(255) NOT NULL DEFAULT "Please add a Description",
percentageComplete DECIMAL(5,2),
numberPassed INT NOT NULL DEFAULT 0,
numberFailed INT NOT NULL DEFAULT 0
) ENGINE=MYISAM;
EDIT 2: This is the code of the SQL query
$numberOfPasses = 5;
$numberOfFails = 5;
$percentageComplete = 100.00;
$sqlquery = "UPDATE `overviewtemplate`
SET numberPassed = {$numberOfPasses},
numberFailed = {$numberOfFails},
percentageComplete = {$percentageComplete}
WHERE description = '{$description}'";
EDIT 3: FIXED - Had a syntax error in my table names which meant it was trying to update a wrong table.
With your declaration you should be able to save even 999.99 without trouble. Check if you have set any rule for it not be bigger than 100? If yes then set it to be less than or equal to 100.00
It could be in a trigger.