Mysql. Query to insert data into a table related to another - java

I'm new in sql. I have doubt. Let's say that I have two tables. One is called user and the other order.
User
User_Id - name - email
Order
Order_id - product - User_id
What query should I use to insert a new order in the order table with the User_id field related to the User_id from the user table(an existing user)
Eg:
Order_id - product - User_id
1a - plate - 1
2a - car - 3
3a - bike - 1

If you have name or email of the user, you can try this. If USER has a composite primary key on user_id and name columns, it will work without any issues. Better to keep foreign key relationship on user_id column of ORDER also.
Example has NAME column, you can try with email column also.
INSERT INTO ORDER (ORDER_ID, PRODUCT, USER_ID)
VALUES (1a, 'plate', (SELECT USER_ID FROM USER WHERE NAME = 'Existing user'));
EDIT:
I have worked on Oracle sql only. After your comment, found this link.
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
If you have defined AUTO_INCREMENT on order_id column, you don't need to pass value.
INSERT INTO ORDER (PRODUCT, USER_ID)
VALUES ('plate', (SELECT USER_ID FROM USER WHERE NAME = 'Existing user'));

you use the standard sql insert.
insert into Order (Order_id, product, User_id) values ("3a", "bike", 1)
If your tables are set up property, there will be a foreign key restriction on the User_id field, so if you try to insert an order but don't reference a valid person, mysql will throw an error.

INSERT order (Order_id, product, User_id) VALUES (1a,plate,1)
The foreign key has nothing to do with the sql used in the insert it should have been set up when the table was created or via an ALTER TABLE query after it was created.

Relationships between tables are defined when you create the table, using the FOREIGN KEY.
CREATE TABLE Users(
UserId int primary key
);
CREATE TABLE Orders(
OrderId int primary key,
UserId int FOREIGN KEY REFERENCES Users(UserId)
);
Then you do a simple insert like:
INSERT INTO ORDER(OrderId, UserId) VALUES(1, 5);
Take a look at the documentation for foreign key constraints here: http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html.

Related

Writing data to tables with relationship in SQL Server

I have two different tables with multiple columns. Like the following
Table1
ID CUSTOMER PRODUCT DETAILS
21 joe phone
22 doe shoe
23 john cup
Table2
PRODUCT ID COST ID
1 9000 21
2 600 22
3 30 23
ID in table1 is primary index and PRODUCT ID in table2 is the primary index. The common link between these two tables is ID. I used the following query to read the values.
String query = "SELECT * FROM Table1 c1 INNER JOIN Table2 c2 ON c1.ID = c2.ID";
But my problem is when I am adding new row, I use the following queries for it.
String query1 = "INSERT INTO Table1(CUSTOMER) VALUES ('" + alex + "') ";
String query2 = "INSERT INTO Table2(COST) VALUES ('" + 500 + "') ";
Since ID is not the primary index for Table2, I get a NULL value in ID. When I try to read again, since ID are not matched the I cannot reload the saved data.
Edit
This is what I have tried based on the explanation given here,
String foreignKey = "ALTER TABLE Table2 ADD FOREIGN KEY (ID) REFERENCES Table1(ID)";
Still the column ID is null in table2. Do I need combine the queries in some sort to acheive the result ? Because I just execute queries one by one as follows.
Statement stmt = connect.createStatement();
stmt.executeUpdate(query1);
stmt.executeUpdate(query2);
stmt.executeUpdate(foreignKey);
General idea here - you need to get autogenerated id from first "insert" to Table1 and set "ID" at Table2 explicitly with this id in the second "insert". You can see how to do that here for example.
Foreign key in your second table - is just a constraint, that helps to prevent data's inconsistency. Its main purpose - is to give some message to you when you're trying to put some data with foreign key that doesn't exist in primary table. Also it can help (if you set this while creating foreign key) to remove from Table2 rows linked on foreign key with Table1 when you delete row at Table1.
And you shouldn't call stmt.executeUpdate(foreignKey); each time you insert data to Table1, Table2. It should be done once when you describe the structure of your database.

How do create a stored procedure to delete an item from a table in Oracle SQL Developer?

I am very new to sql, and I am trying to delete a row of person data from a BANK_PERSON table along with its FK constraints. I am using JDBC to declare a callable statement, which takes in a username, then calls a stored procedure in sql and deletes a person from the database.I know the basic process for creating a stored procedure, but I'm not sure how to do it in my case . Here is my BANK_PERSON table and MY BANK_ACCOUNT table with an FK constraint.
CREATE TABLE BANK_PERSON (
ID_NUMBER INTEGER PRIMARY KEY,
FIRSTNAME VARCHAR2(30),
LASTNAME VARCHAR2(30),
USERNAME VARCHAR2(30),
PASS VARCHAR2(30),
RANK INTEGER
);
CREATE TABLE BANK_ACCOUNT (
ACCOUNT_NUMBER INTEGER PRIMARY KEY,
ACCOUNT_BALANCE NUMBER(10,2),
FOREIGN KEY(ACCOUNT_NUMBER) REFERENCES BANK_PERSON(ID_NUMBER));
First of all I suggest to use ON DELETE CASCADE option for your FK which allows you delete all child entries automatically. In other words use following script for creation of BANK_ACCOUNT table:
CREATE TABLE BANK_ACCOUNT (
ACCOUNT_NUMBER INTEGER PRIMARY KEY,
ACCOUNT_BALANCE NUMBER(10,2),
FOREIGN KEY(ACCOUNT_NUMBER) REFERENCES A1(ID_NUMBER) ON DELETE CASCADE);
Then use following script for procedure creation:
CREATE OR REPLACE
PROCEDURE DELETE_PERSON
(USERNAME IN VARCHAR2) AS
BEGIN
delete from BANK_PERSON where BANK_PERSON.USERNAME like DELETE_PERSON.USERNAME;
END DELETE_PERSON;
And finally call of newly created procedure:
EXECUTE DELETE_PERSON('Marcus');
Hope this is what you would like to get.

MySQL Get value inserted by trigger in Java

Using MySQL, I have the following SQL Table definition:
CREATE TABLE books (
author INT,
book INT,
name VARCHAR(128),
PRIMARY KEY(author, book)
);
What I want is that I have an Id for author that I set manually and an Id for book that is incremented for each author id. Therefore I created a trigger like so:
CREATE TRIGGER trBooks
BEFORE INSERT ON books
FOR EACH ROW SET NEW.book = (
SELECT COALESCE(MAX(book), -1) + 1 FROM books
WHERE author = NEW.author
);
This works fine for me. But now I need to know the book id that was set for my inserted entry that I inserted in Java. Something like the Insert with Output as in MSSQL or a Statement.executeQuery("INSERT ..."). The solution has to be thread safe, so a separate INSERT and SELECT is no good solution, since there might have been another INSERT in the meantime.
Thanks for your help!
Your data model just doesn't make sense. You have two entities, "books" and "authors". These should each be represented as a table. Because a book can have multiple authors and an author can write multiple books, you want a junction table.
This looks like this:
CREATE TABLE Books (
BookId INT auto_increment primary key,
Title VARCHAR(255)
);
CREATE TABLE Authors (
AuthorId INT auto_increment primary key,
Name VARCHAR(255)
);
CREATE TABLE BookAuthors (
BookAuthorId INT auto_increment primary key,
AuthorId INT,
BookId INT,
CONSTRAINT fk_BookAuthor_BookId FOREIGN KEY (BookId) REFERENCES Books(BookId),
CONSTRAINT fk_BookAuthor_AuthorId FOREIGN KEY (BookId) REFERENCES Authors(AuthorId),
UNIQUE (AuthorId, BookId)
);
As for your question about inserts. You don't need a trigger to set auto-incremented ids. You can use LAST_INSERT_ID() to fetch the most recent inserted value.

H2 sql how to set column to auto_increment

i am trying to set my ID to auto_increment, but it is not doing it. i saved 2 more data into db, all are still getting 0 id. as a result i am not able to set ID as primary key.
how is it possible? can i set the field to auto_increment with JPA annotation or so?
i even tried this command which is the first attempt:
alter table user alter column id int not null auto_increment;
no affect.
can someone help me please
thanks in advance!
If you just want to set ID as a primary key which is auto generated,then sql uniqueidentifier for it.
CREATE TABLE userTable(userId uniqueidentifier primary key, userName nvarchar(50))
--create a table having userId as a primary key
INSERT INTO userTable(userId, userName ) VALUES (NEWID(), 'mohit');
INSERT INTO userTable(userId, userName ) VALUES (NEWID(), 'doniyor');
SELECT * FROM userTable
Result will be:
userId userName
{E8E0A79D-436F-49CB-BCEC-EC9E5D69F1BB} mohit
{21081DFA-7DBB-46AF-A160-550631160C25} doniyor

auto creat table row when other table add row

i have 2 table
1 persons(email,name)
2 location(email)
now when i add a person to persons table i want the db auto creat a row in location whit the person email (that i just add to persons).
i try to do it white PRIMARY KEY, and FOREIGN KEY but no succses.
thank you all.
this what i try :
CREATE TABLE Persons
(
Email char(50) PRIMARY KEY,
First_Name char(50))
CREATE TABLE location
(
email char(50),
FOREIGN KEY (email) REFERENCES Persons(email)
)
but when i add to persons person its not added to location too.
You would need a trigger to do this not a foreign key.
The FK just enforces that a row cannot be inserted in location without a corresponding record in Persons
But email is a very wide choice for a primary key as well as unstable (see is email address a bad primary key) and the whole design seems odd.
What is the location table for? Does this have a 1:many relationship with Persons? Where are the other columns? What is the PK of location?

Categories