MySql Database inserting data - mysql

I have a MySQL database with 9 tables, each table has an id with primary key set and auto increment and a row for data, one table let's call it 'X' from this database has also a primary key and one row for data and all primary keys from other tables as foreign keys, the question is can I insert into 'X' table not by id of other tables but by data row, for example some other tables has id -> 3 and data: apple , can I insert 'apple' that takes id 3, instead of id 3 that takes apple from data row ?

You can select and insert values in one step:
INSERT INTO X (fruit_id, ...)
VALUES ((SELECT fruit_id FROM fruits WHERE fruit = 'apple'), ...);
That will insert the fruit_id of apple.
Based on i486s comment, you can also directly insert a select result:
INSERT INTO X (fruit_id, tableb_id, tablec_id, datafiled)
SELECT fruit_id, b.tableb_id, c.tablec_id, 'some data'
FROM fruits a, tableb b, tablec c
WHERE a.fruit = 'apple',
AND b.tableb_data = 'some data from tableb'
AND c.tablec_data = 'some data from tablec';

No, mysql is no ms access where you could do this. You can implement an import function in mysql or even a GUI in another programming language that translates the value 'apple' into the foreign key of 3 by looking it up in the other table. That's exactly what ms access does in the background for you.

Related

I have a SQL query that loops data

I wrote a query to display certain record, but it is displaying extra data, for instance I have only 239 records in my database, but the query is displaying 356 records. Can anyone advice me on what I did wrong, I would really appreciate it. Here is the query:
SELECT DISTINCT
t.branchid,
t.occupancyid,
t.wardnumber,
t.bednumber,
t.admissiondate,
ti.patientname
FROM
bedoccupancydetail t
JOIN
consultationheader ti ON t.occupancyid = ti.occupancyid
WHERE
t.checkedout = '0'
There might not be any problem with your query, just it is how mysql (or any RDBMS) behaves. In your case in the two tables bedoccupancydetail and consultationheader are joined by occupancyid and it seems this columns is not unique and contains duplicate values, for each matching (duplicate) record it adds a row/record after joining.
Let's see the below example which I run at https://www.tutorialspoint.com/execute_sql_online.php:
BEGIN TRANSACTION;
CREATE TABLE NAMES(Id integer PRIMARY KEY, Name text);
INSERT INTO NAMES VALUES(1,'Tom');
INSERT INTO NAMES VALUES(2,'Lucy');
INSERT INTO NAMES VALUES(3,'TOM');
INSERT INTO NAMES VALUES(4,'TOM');
CREATE TABLE ABC(Id integer PRIMARY KEY, Name text, Another text);
INSERT INTO ABC VALUES(1,'Tom', 'A');
INSERT INTO ABC VALUES(2,'Lucy', 'B');
INSERT INTO ABC VALUES(3,'TOM', 'C');
INSERT INTO ABC VALUES(4,'TOM', 'D');
COMMIT;
/* Display all the records from the table */
SELECT ABC.Name, NAMES.Name, ABC.Another
FROM NAMES
JOIN ABC on ABC.Name = NAMES.Name;
As you see each table has 4 rows but the result has 6 rows:
$sqlite3 database.sdb < main.sql
Tom|Tom|A
Lucy|Lucy|B
TOM|TOM|C
TOM|TOM|D
TOM|TOM|C
TOM|TOM|D

SQL normalized data INSERT WHERE NOT EXISTS ; ON DUPLICATE KEY UPDATE

i am using MySql Workbench version 6.3.9 with mySql 5.6.35.
i have the following tables:
EQUIPMENT
eID | caochID | eName
COACH
coachID | coachName
SQLfiddle prepared http://sqlfiddle.com/#!9/e333d/1
eID is a primary key. there are multiple coachID's in different equipment, so there will be duplicate coachIDs with different equipment, but the eID will be unique as it is a primary key.
REQUIRED
i need to insert a row in the equipment table, if it does not already exist. If it exists, do nothing.
various posts online have pointed me towards two options:
a) INSERT...ON DUPLICATE KEY UPDATE...
b)INSERT...WHERE NOT EXISTS
PROBLEM i have problems with both of these solutions. for the first solution (ON DUPLICATE KEY UPDATE) the query inserts the row as required but does not update the existing row. instead it creates a new entry. for the second solution (WHERE NOT EXISTS) i get an error : SYNTAX ERROR: 'WHERE' (WHERE) is not a valid input at this position.
the sql query doesnt need to make any joins. i listed both tables so that you can see how they are related. the insert query i need will only insert for the equipment table.
You can insert by using a tmp table and ensuring that the same record is not existing from current table. Add limit 1 to ensure only one record is inserted. Below query will not insert since 1 and small ball exists.
INSERT INTO `Equipment` (`c_id`, `eName`)
SELECT * FROM (SELECT '1', 'small ball') tmp
WHERE NOT EXISTS (
SELECT c_id FROM Equipment WHERE `c_id`='1' and `eName` = 'small ball'
) LIMIT 1;
NOT EXISTS
insert into table2 (....) --- all if not columns ... destination
select ....
from table1 t1 --- source of data to check
where not exists (
select 1
from table2 t2
where t2.col = t1.col --- match source and destination table making sure table1 data is not in table2
)

Inserting data into table SQL server

If I have 2 tables and Table 1 has a primary key(userID) AutoIncrement and Table 2 has a foreign Key(userID) to Table 1's (userID)
When I insert a new row into Table 1 first row will have userID = 1
Then if I insert again, userID = 2.
So how do I go about keeping Table 2's userID the same when inserting in Table 1. For instance, in Table 2, I am adding the password into another table.
My question is should I add an AUTOINCREMENT to Table 2(userID) and insert a new value into both tables when I create a user OR is there another way?
You have to manually insert data with correct id in Table2. There is no such built-in functionality in MySQL.
The algorithm is as follows:
Insert row in Table1.
Get Id of the new row.
Insert row with new id in Table2.
I think what you are looking for is this ... Assuming your ID is PK and AI
INSERT INTO yourTable (var1, var2 etc etc) VALUES ('val1', 'val2' etc etc);
SELECT LAST_INSERT_ID();
To further it ..
INSERT INTO yourTable (var1, var2 etc etc) VALUES ('val1', 'val2' etc etc);
SET #last_id = LAST_INSERT_ID();
INSERT INTO yourTable2 (id, var1, var2) VALUES (#last_id, 'blah', 'blah');

How to insert values in table with foreign key using MySQL?

I have these two tables just for example:
TAB_TEACHER
- id_teacher // primary key, autoincrement
- name_teacher // a varchar
TAB_STUDENT
- id_student // primary key, autoincrement
- name_student // a varchar
- id_teacher_fk // foreign key reference to a teacher (TAB_TEACHER)
I want to know how to insert in these two cases:
CASE 1 - INSERT a new Student with an pre-existing TEACHER, so I have to get the foreign key with a teacher name
CASE 2 - INSERT a new Student with a new TEACHER (the teacher I'm creating in the same time I'm creating the student)
http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
For case1:
INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
SELECT 'Joe The Student', id_teacher
FROM TAB_TEACHER
WHERE name_teacher = 'Professor Jack'
LIMIT 1
For case2 you just have to do 2 separate insert statements
Case 1: Insert Row and Query Foreign Key
Here is an alternate syntax I use:
INSERT INTO tab_student
SET name_student = 'Bobby Tables',
id_teacher_fk = (
SELECT id_teacher
FROM tab_teacher
WHERE name_teacher = 'Dr. Smith')
I'm doing this in Excel to import a pivot table to a dimension table and a fact table in SQL so you can import to both department and expenses tables from the following:
Case 2: Insert Row and Then Insert Dependant Row
Luckily, MySQL supports LAST_INSERT_ID() exactly for this purpose.
INSERT INTO tab_teacher
SET name_teacher = 'Dr. Smith';
INSERT INTO tab_student
SET name_student = 'Bobby Tables',
id_teacher_fk = LAST_INSERT_ID()
Case 1
INSERT INTO tab_student (name_student, id_teacher_fk)
VALUES ('dan red',
(SELECT id_teacher FROM tab_teacher WHERE name_teacher ='jason bourne')
it is advisable to store your values in lowercase to make retrieval easier and less error prone
Case 2
mysql docs
INSERT INTO tab_teacher (name_teacher)
VALUES ('tom stills')
INSERT INTO tab_student (name_student, id_teacher_fk)
VALUES ('rich man', LAST_INSERT_ID())

insert if not exists else just select in mysql

I have one mysql table 'alfa' that will contain the primary key of another table 'beta' in one column. But if the entry in 'beta' can not be found I want to insert the value in 'beta' and use the new key in 'alfa'. Can I do this in one query somehow ?
I currently have:
INSERT INTO alfa SET c1=(SELECT id FROM beta WHERE name = 'john');
which works fine when 'john' exists in the table, but fails otherwise. So could I improve it to let the new name be inserted and selected if it is not already there ? id is auto_incremented.
I have tried to looking at IF but have not yet found out how to use IF outside the SELECT, is that possible ?
I know I can do it in several queries but I am talking with a remote database so could be nice to do it all at once.
For example the tables could have been created like this:
CREATE TABLE alfa (
c1 int,
PRIMARY KEY (c1)
)
CREATE TABLE beta (
id int auto_increment,
name varchar(255),
PRIMARY KEY (id)
)
so alfa.c1 should refer to the beta.id values.
In short I want to do:
insert the id for john from the beta table into c1 in alfa, if john does not exist in beta then insert john into beta and insert the new auto incremented id for john into c1 in alfa.
I'll have a go, but bear in mind that coming from a Microsoft SQL background, and I'm not familiar with the exact structure of your tables, so some of the the SQL is probably a bit ropey.
IF (SELECT COUNT(*) FROM beta WHERE name = 'John' > 0)
UPDATE alfa SET c1=(SELECT id FROM beta WHERE name = 'John')
ELSE
BEGIN
INSERT INTO beta (name) VALUES ('John')
INSERT INTO alfa (c1) VALUES (LAST_INSERT_ID())
END
Hope this is of some help.