i got the following insert-command:
INSERT INTO PERSON ('Name','Age','Filename') VALUES ('Max',12,'Max_ID_.pdf');
i want to insert instead of 'Max_ID_.pdf' the string concartenated with the inserted id for this row. e.g.:
ID|Name|Age|Filename
2 |Max |12 |Max_2_.pdf
You can insert your row first, and than update it with the last inserted id:
INSERT INTO PERSON ('Name','Age','Filename') VALUES ('Max',12,'xxx');
UPDATE PERSON Filename=CONCAT(LAST_INSERT_ID(),'.pdf') where id = LAST_INSERT_ID()
There is also a way to do it in one statement, maybe a little more complex, and maybe will not work on every system, e.g. if you use innodb or transactions:
INSERT INTO PERSON SET Filename = CONCAT((SELECT auto_increment FROM
information_schema.tables WHERE table_name='PERSON'), '.pdf'),
Name = 'Max', Age = '12'
Related
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
How to insert score with value and score_id ? At server im know only score_type.name and score.value. How i can insert new score with score_type ? If score_type name exsist just get id and insert, else create, get id and insert.
First try to create the score_type if it doesn't exist:
INSERT IGNORE INTO score_type (name) VALUES ("type_name");
Then use INSERT ... SELECT to insert the ID into the score table:
INSERT INTO score (value, score_type_id, player_id)
SELECT 123, id, "player_name"
FROM score_type
WHERE name = "type_name";
The first INSERT assumes you have a unique index on score_type.name. IGNORE means to fail silently if you try to insert a duplicate name.
Replace 123 and player_name with the known score.value and score.player_id.
If I understood your question correctly, you want to fill the score_type_id dynamically by selecting it using the name:
INSERT INTO `score`(`value`, `score_type_id`, `player_id`) VALUES (1337, (SELECT id FROM score_type WHERE score_type.name = "test") ,"maio290");
The trick is just to use another query instead of a fixed value.
I am trying to insert multiple rows into two tables connected by a foreign key that is autoincrement. I can't seem to find a good solution.
Tables:
eav_attribute_option
option_id (PK, Autoincrement)
attribute_id
sort_order
eav_attribute_option_value
value_id (PK, Autoincrement)
option_id (FK)
store_id
value
I want to do this:
insert into eav_attribute_option(attribute_id) values(100,101,102,103,...);
insert into eav_attribute_option_value(option_id,store_id,value) values
(1,0,"English"),(1,1,"German"),(2,0,"English1"),(2,1,"German2")
What would be the best approach to this, I can't seem to find a good one. :
Get next autoincrement then insert with it (need to lock table between)
Insert first part, then retreive PK values, build second part and insert (data incomplete for some time, what happens on error in second part?)
Some way to insert with join if it's possible?
Edit:
Just to clarify, I am looking to use the least amount of queries possible. I know I can do last inserted id, but I don't want to kill the server with thousands of inserts.
You can try something like this:
insert into eav_attribute_option (attribute_id) values(100);
insert into eav_attribute_option_value (option_id, store_id, value)
values (LAST_INSERT_ID(), 0, "English");
But you will need to insert the rows one by one. Consider doing a loop in your application.
$count = count('Count post value'); // $_POST value count
for($a=0;$a<$count;$a++)
{
$insert = 'insert into eav_attribute_option(attribute_id,sort_order) values (value1,value2)';
mysql_query($insert);
$insert_id = mysql_insert_id();
$insert2 = 'insert into eav_attribute_option_value(option_id,store_id,value) values
($insert_id,0,"English")';
mysql_query($insert2);
}
I have a MySQL table like this,
id (primary key) | name | scores
and I am reading a large file to insert records into the MySQL table.
New records will be added into this file but the old records are not deleted, so when I read the file, a lot of records are already in the database.
Except to use SELECT COUNT to see if a record is already in the database, is there a best way to check it (to save processing time & database load)?
Or maybe I should just INSERT it directly? (The database will not allow records with duplicate id anyway.)
I usually use update + insert method.
first i will run the update statement. the update query will act like a select query + directly update the data.
update t1 set t1.Name = 'Name', t1.Scores = 99
where t1.Name = 'Name' and t1.Scores = 99
then check if there is a row affected by the above query. if not run the insert statement
if ##RowCount = 0
insert into t1 (Name, Scores) values ('Name',99)
Serch examples for
INSERT IGNORE INTO table
Simple example for this is
INSERT IGNORE INTO `transcripts`
SET `ensembl_transcript_id` = ‘ENSORGT00000000001′,
`transcript_chrom_start` = 12345
`transcript_chrom_end` = 12678;
I have a table (foo) where I already have a PK on id:
id name rank
-----------------------
1 AAAA 2
2 BBBB 1
I want to insert a new row where I know the values of column id and name and want rank to take a value greater than any other value in the same column in preceding rows (similar to what auto_increment does for us).
i.e. if I were to add a row with value = CCCC, the rank column should have a value 3. I need to do this in a compound statement if possible. I tried the following which does not work.
insert into foo (`name`, `rank`)
values ('CCCC', (select max(`rank`) from `foo`))
Which gives me the following error:
You can't specify target table 'foo' for update in FROM clause
Note: I would ideally like to have the rank column as an auto_increment field, but apparently that's not allowed either, since I already have a PK.
PS: I need to be able to execute this statement from PHP without using stored procedures.
Try this first, it being derived instantly from your post:
INSERT INTO foo (`name`, `rank`)
SELECT 'CCCC', (MAX(`rank`) + 1) AS rank
FROM `foo`
Then using PDO, I think this'll work:
...
$sql = "INSERT INTO foo (`name`, `rank`) SELECT ?, (MAX(`rank`) + 1) AS rank FROM `foo`"
$name = "CCCC";
$st = $pd->prepare($sql);
$st->bindValue(1, $name);
try {
$retval = $st->execute();
} catch (PDOException $pdoex) {
...
Not sure if I got in syntactically correct but that should be about the gist of it ... I think
Err.. lemme know if the SQL works, at least :D