MySQL: Created Table won't show values? - mysql

I'm new to MySQL and I created a table called students with some attributes but when I run Select * From Students it appears as null for each category I'm not sure why
use practice;
create table Students(
sid integer default 1,
sname varchar(50) default 'Joe',
GPA real default 1.7,
dateOfBirth date default (2000-12-12),
primary key(sid)
);
select *
from Students

You can try to insert a value in your table (Insert into Students ('sid', 'sname', 'GPA', 'dateOfBirth') Values ('NULL', 'joe', '1.7', '200-12-12'); this will solve your problem with the SELECT *
I would also add an auto increment on your sid so you can putt the value of sid to null and it will automatically ALTER TABLE Students MODIFY 'sid' INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY;

Related

Nothing shows when I use select *

I created some tables but when I want to check if my data is inside it doesn't show anything when
I use select * from Project it just appears null and I don't have null values I'm not sure what I'm doing wrong it just appears that the foreign key is restrict
`create table Department
(
`did integer not null auto_increment,
Dname varchar(50) default 'HR',
location varchar(50) default 'Chicago',
primary key(did)`
);
`create table Employee`
(
Eid integer not null auto_increment,
DepartmentID integer default 5,
Ename varchar(50) default 'Josh',
Erank integer default 2,
Salary real default 5000.00,
primary key(Eid),
foreign key(DepartmentID) references Department(did)
);
/*drop table Project;*/
create table Project
(
Pid integer not null auto_increment,
DepartmentID integer default 5,
Pname varchar(50) default 'Sorting',
budget real default 5000.00,
StartYear integer default 2000,
primary key(Pid),
foreign key(DepartmentID) references Department(did)
);
insert
into Project(DepartmentID, Pname, budget, StartYear)
values(1, 'OS', 5000.00, 2018),
(2, 'Net', 6000.00, 2020);
select *
from Project;
Check this fiddle. There are no rows in Department, so the restraint keeps the insert into Projects from happening. Also, I removed the backticks:
https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=64f8f0e9cccce2eb2ab77b37fcce54fd
Add COMMIT statements:
create table Project...
commit;
insert into Department values('HR','Chicago');
insert into Department values('Admin','New York');
insert into Project...
commit;
select * from Project;

How do I add data from different tables into one new table in mySQL?

CREATE TABLE CU_ORDER
( cordernumber INT PRIMARY KEY,
fname_lname VARCHAR(50) NOT NULL,
product_name VARCHAR(100) NOT NULL,
);
CREATE TABLE TRACKING_NUMBER
( trnumber INT PRIMARY KEY
);
INSERT INTO CU_ORDER VALUES(456, 'John Doe' , Table);
INSERT INTO TRACKING_NUMBER(276734673);
I am trying to created a table called Package and in the table it will have all the items from cu_order and all the items from tracking_number. How will I add all of the attributes of this table to one table. What am I doing wrong?
CREATE TABLE PACKAGE
( orderno INT PRIMARY KEY,
fname VARCHAR(50) NOT NULL,
name VARCHAR(100) NOT NULL,
trno INT PRIMARY KEY);
INSERT INTO PACKAGE (........
The two tables do not seem to have a relation, so, presumably, you want a cartesian product of both tables. If so, you can use the insert ... select ... syntax with a cross join:
insert into package(orderno, fname, name, trno)
select
co.cordernumber,
co.fname_lname,
co.product_name,
tn.trnumber
from cu_order co
cross join tracking_number tn
This inserts all possible combinations of rows from both source tables in the target table.
You should also fix the declaration of the package table: yours has two primary keys, which is not allowed. Instead, you probably want a compound primary key made of both columns:
create table package (
orderno int,
fname varchar(50) not null,
name varchar(100) not null,
trno int,
primary key(orderno, trno)
);
You can create a new table from the data of another table (or several tables) by appending a SELECT statement to the CREATE TABLE statement.
However, your two source tables are missing the 1:1 relation allowing this to work, which I assume is the cordernumber of CU_ORDER. It appears the table TRACKING_NUMBER is missing a 'cordernumber' column.
CREATE TABLE TRACKING_NUMBER (
trnumber INT PRIMARY KEY,
cordernumber INT
);
After you added the column 'cordernumber' to TRACKING_NUMBER, you can create the new table PACKAGE with:
CREATE TABLE PACKAGE (
orderno INT PRIMARY KEY,
fname VARCHAR(50) NOT NULL,
name VARCHAR(100) NOT NULL,
trno INT PRIMARY KEY
)
SELECT
CU_ORDER.cordernumber AS orderno,
CU_ORDER.fname_lname AS fname,
CU_ORDER.product_name AS name,
TRACKING_NUMBER.trnumber AS trno
FROM CU_ORDER, TRACKING_NUMBER
WHERE CU_ORDER.cordernumber=TRACKING_NUMBER.cordernumber;

Update row in first table and insert a row into a second table in a single query

I'm trying to figure it out how to insert a row into a table on updating a particular field in the second table.
Let's say I have table 1 (dif):
CREATE TABLE dif
(
Position INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
pKey SMALLINT(3) UNSIGNED NOT NULL,
Number SMALLINT(3) UNSIGNED DEFAULT 0 NOT NULL
);
ALTER TABLE dif
ADD CONSTRAINT dif_article_pKey_fk
FOREIGN KEY (pKey) REFERENCES article (pKey) ON UPDATE CASCADE;
and table 2 (article):
CREATE TABLE IF NOT EXISTS article (
pKey smallint(3) unsigned NOT NULL AUTO_INCREMENT,
Name varchar(80) COLLATE utf8_roman_ci NOT NULL,
Number SMALLINT NOT NULL DEFAULT 0
PRIMARY KEY (pKey)
);
The table article is populated with some data and should be only updated. Table "dif" is empty at the beginning. So, let's say I'm updating the fields on "article" like this:
UPDATE article SET pKey = 15, Name = SomeName, Number = 22 WHERE pKey=15;
Can I somehow combine the UPDATE query with this?
INSERT INTO dif (pKey, Number) VALUES (15, 12);
The "12" is the difference between the "article.Number" before and after UPDATE.
No, but you can make a stored procedure that does both of those things and then execute it in a single statement.
create procedure GiveThisABetterName
(
in pKey int,
in newNumber int,
in currentNumber int,
in newName varchar(100)
)
begin
update
article
set
Name = newName, Number = newNumber
where
pKey = pKey;
insert into dif (pKey, Number) values (pKey, newNumber);
end
My mysql syntax is rusty, but that should be close. Then when you want to execute it:
call GiveThisABetterName(12, 15, 22, 'Some Name');
EDIT: After reading your question again, it seems to me that you're trying to make your data model track audit information that it's just not set up to accommodate naturally. Do you have control over the model? If so, consider something like this (see here for a working example of what's below):
CREATE TABLE IF NOT EXISTS article (
pKey smallint(3) unsigned NOT NULL AUTO_INCREMENT,
Name varchar(80) COLLATE utf8_roman_ci NOT NULL,
PRIMARY KEY (pKey)
);
CREATE TABLE ArticleNumbers
(
Counter int UNSIGNED PRIMARY KEY AUTO_INCREMENT,
pKey SMALLINT(3) UNSIGNED NOT NULL,
Number SMALLINT(3) DEFAULT 0 NOT NULL,
Difference SMALLINT(3)
);
ALTER TABLE ArticleNumbers
ADD CONSTRAINT ArticleNumbers_article_pKey_fk
FOREIGN KEY (pKey) REFERENCES article (pKey) ON UPDATE CASCADE;
Maybe add a few views to make things easier:
CREATE VIEW GroupedArticleNumbers
as
select pKey, max(Counter) as Counter
from ArticleNumbers
group by pKey;
CREATE VIEW CurrentArticles
as
select article.pKey, article.Name, numbers.Number, numbers.Difference
from article
left outer join GroupedArticleNumbers filter on article.pKey = filter.pKey
left outer join ArticleNumbers numbers on filter.Counter = numbers.Counter;
Since you can track the number separately from the base record now but still easily determine what the current number is, you can now combine your update and insert statement functionality. See below.
First, some test data:
insert into article (Name) values ('Test');
insert into ArticleNumbers (pKey, Number, Difference) values (1, 10, null);
insert into ArticleNumbers (pKey, Number, Difference) select 1, 20, 20 - Number from CurrentArticles where pKey = 1;
insert into ArticleNumbers (pKey, Number, Difference) select 1, 50, 50 - Number from CurrentArticles where pKey = 1;
insert into ArticleNumbers (pKey, Number, Difference) select 1, 15, 15 - Number from CurrentArticles where pKey = 1;
See how nicely that works out once the overhead of setting up the schema has been done?
To get the current number for the article we created:
select * from currentarticles where pKey = 1
To get the number history for that article:
select * from article
left outer join articlenumbers on article.pkey = articlenumbers.pkey
order by counter asc
If you're willing to mess with your data model, you can have an alternative to stored procedures.
Alternatively, if you want to use triggers as #Jonathan Leffler suggested, something like this should work:
CREATE TABLE article (
pKey smallint(3) unsigned NOT NULL AUTO_INCREMENT,
Name varchar(80) COLLATE utf8_roman_ci NOT NULL,
Number SMALLINT(3) DEFAULT 0 NOT NULL,
PRIMARY KEY (pKey)
);
CREATE TABLE ArticleNumbers
(
Counter int UNSIGNED PRIMARY KEY AUTO_INCREMENT,
pKey SMALLINT(3) UNSIGNED NOT NULL,
Number SMALLINT(3) DEFAULT 0 NOT NULL,
Difference SMALLINT(3)
);
delimiter $
create trigger tr_u_article
before update on article
for each row
begin
insert into ArticleNumbers (pKey, Number, Difference) select old.pKey, new.Number, new.Number - old.Number
end;
delimiter ;

Auto_increment trigger

I need to auto_increment the primary key in a mysql database using a trigger. Unfortunately, I am not quite sure how to do this. In the sample code I have provided, I need the employee table primary key to auto_increment beginning with an empty table and a starting value of 200. Then, I need each new insert to increment by 1.Thanks for looking and I hope you are able to help me.
CREATE TABLE department (
dept_name VARCHAR(50) NOT NULL Primary Key
);
CREATE TABLE employee (
emp_id INT(6) unsigned Default 0 Not NULL
, last_name VARCHAR(25) NOT NULL
, first_name VARCHAR(40) NOT NULL
, dept_name VARCHAR(50) NOT NULL
, PRIMARY KEY(emp_id, dept_name)
, FOREIGN KEY(dept_name) REFERENCES department (dept_name)
);
There are several things you need to do:
Declare the emp_id column as AUTO_INCREMENT;
Set the value of AUTO_INCREMENT property of the table to 200;
Do not provide any value for column emp_id when you INSERT rows in table employee.
Change the table creation as below:
CREATE TABLE employee (
emp_id INT(6) UNSIGNED NOT NULL AUTO_INCREMENT,
last_name VARCHAR(25) NOT NULL,
first_name VARCHAR(40) NOT NULL,
dept_name varchar(50) NOT NULL
PRIMARY KEY(emp_id),
FOREIGN KEY(dept_name) REFERENCES department_tbl(dept_name)
) AUTO_INCREMENT=200;
If the table has an AUTO_INCREMENT column then it must be the PRIMARY KEY of the table. I removed dept_name from the definition of the PK above. I also removed the default value 0 from the emp_id column. It's default value is generated by MySQL using the AUTO_INCREMENT policy.
When you INSERT a new record into the employee table all you have to do is to not provide any value for the emp_id column:
INSERT INTO employee (last_name, first_name, dept_name)
VALUES ('Doe', 'John', 'accounting');
Then use the LAST_INSERT_ID() MySQL function to retrieve the value of the emp_id generated on insertion.
The language or the library you use to develop the client application probably has a function that wraps LAST_INSERT_ID() and returns its value.

MySQL many-to-many: Insert into table and then into junction table?

I have 3 tables: persons, places and person_place.
Each person can have many favorite places, just as each place can be "favorited" by many persons/people.
CREATE TABLE persons
(
ID int NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL
//some fields omitted
);
CREATE TABLE places
(
ID int NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
address VARCHAR(50) NOT NULL
//some fields omitted
);
CREATE TABLE person_place
(
ID int NOT NULL AUTO_INCREMENT,
personID int NOT NULL, //references persons.id
placeID int NOT NULL //references places.id
)
Let's say a user favorites a new place (by some web page).
How should I insert the new place and then get it's id in order to add the person_place row?
Thank you.
I would wrap the inserts inside a transaction and then use LAST_INSERT_ID() to get the id of the last inserted item.
START TRANSACTION;
INSERT INTO places(name,address) VALUES('someplace', '...');
SET #last_inserted_id = LAST_INSERT_ID();
INSERT INTO person_place (personID, placeID) VALUES (1, #last_inserted_id)
COMMIT;
I believe in MySQL you would use the LAST_INSERT_ID() function.