Passing values to the insert query with select query - mysql

I want to insert two values in the a table.One of which is actually taken from another table with the select statement as below.
query = "INSERT INTO empallowance(emp_id_fk,allowance_id_fk) VALUES(SELECT emp_id FROM employee WHERE emp_cnic='" + cnic + "',#allowance_id_fk)";
There is syntax error exception as shown in the figure.

Your SQL statement is invalid. Use the following:
query = "INSERT INTO empallowance SELECT emp_id, #allowance_id_fk FROM employee WHERE emp_cnic='" + cnic + "'";
You can read all about the approach here.

you have to use bracket in sub query.
try this:
query = "INSERT INTO empallowance(emp_id_fk,allowance_id_fk) VALUES((SELECT emp_id FROM employee WHERE emp_cnic='" + cnic + "'),#allowance_id_fk)";

You can modify your query as below :
query = "INSERT INTO empallowance(emp_id_fk,allowance_id_fk) SELECT emp_id, #allowance_id_fk FROM employee WHERE emp_cnic= ' " + cnic + "'";

Add '()' between select query for a separation of insertion query.
INSERT INTO empallowance(emp_id_fk,allowance_id_fk) VALUES((SELECT emp_id FROM employee WHERE emp_cnic='" + cnic + "'),#allowance_id_fk)

You can't do it that way but you can create a select statement and insert its results:
"INSERT INTO empallowance (emp_id_fk,allowance_id_fk)
select emp_id, #allowance_id_fk
from employee
WHERE emp_cnic='" + cnic + "'"
Also, take note, using string concatenation to insert the parameter is vulnerable for SQL Injections - Use parameterized queries instead

You can easily do this by this, it worked for me
query = "INSERT into TABLE1 (name,city)
Select name, 'Paris' from TABLE2 where id = 1";
you can assign values directly in a select query.

Related

Nodejs and SQL - Issue with inserting data to SQL using multiple select statements

Error image
While inserting the data in SQL database table user_recipe_consumption by using multiple select statements i am facing error as - throw err; // Rethrow non-MySQL errors
^
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Mushroom pasta');' , '( select vegEmission from RecipeEmissions where RecipeName' at line 1
for (var dataVal = 0; dataVal < req.body.length; dataVal++) {
var recipeInfo = req.body[dataVal].RecipeName;
var deviceID = req.body[dataVal].deviceID;
var totEmission = req.body[dataVal].totalEmission;
var sql = "INSERT INTO user_recipe_consumption (deviceID, totalEmission, recipeID , vegEmission,date_of_entry) VALUES ('" + deviceID + "','" + totEmission + "', '( select RecipeID, from RecipeEmissions where RecipeName = ?);' , '( select vegEmission from RecipeEmissions where RecipeName = ? );' ,'" + now + "')";
con.query(sql, recipeInfo, function(err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
}
Instead of SQL with var concated (and related problem with data type and SQL injection) you should use a query completely based on param binding (eg: named param). You should also use a insert select syntax instead of several select from the same table
"INSERT INTO user_recipe_consumption (deviceID, totalEmission, recipeID , vegEmission,date_of_entry)
SELECT :deviceID, :totEmissino, RecipeID, vegEmission, :date_of_entry
FROM RecipeEmissions
where RecipeName = :RecipeName;"
eg:
connection.execute(
"INSERT INTO user_recipe_consumption (deviceID, totalEmission, recipeID , vegEmission,date_of_entry)
SELECT :deviceID, :totEmission , RecipeID, vegEmission, :date_of_entry
FROM RecipeEmissions
WHERE RecipeName = :RecipeName;",
{deviceID: deviceID, totEmission: totEmission, date_of_entry:date_of_entry,RecipeName:RecipeName},
function(err, result)
.......
You have too many semicolons in your SQL statement. You're also putting single-quotes around a subquery, which effectively turns it into a string literal. And you're using NOW() incorrectly. Try this:
var sql = "INSERT INTO user_recipe_consumption (deviceID, totalEmission, recipeID , vegEmission,date_of_entry) VALUES ('" + deviceID + "','" + totEmission + "', ( select RecipeID, from RecipeEmissions where RecipeName = ?) , ( select vegEmission from RecipeEmissions where RecipeName = ? ) , NOW())";
If you mean now to be a JS variable then you can revert that part of the query to what you had originally, but it's not clear what now is supposed to contain.

How to achieve TRIM on a SELECT * query

MySQL's TRIM function works great when specifying a particular column name, as in:
SELECT TRIM( BOTH "'" FROM channelurl ) FROM posts
I need to achieve the same result when doing a "SELECT *" query.
This does not work:
SELECT TRIM( BOTH "'" FROM * ) FROM posts
Is there a one-step process like this that achieves this outcome?
you have have to specify the fields to trim,
SELECT TRIM(BOTH "'" FROM field1) as field1, TRIM(BOTH "'" FROM field2) as field2 FROM posts
for example if you have an auto_increment field in the table it wont work in the trim function.

MySqlDataReader reads data when there is sum(a+b) in the query

When I use this query
("SELECT id, at_date AS MyDate , nom, pax, SUM(prix*pax) AS somme,
SUM(pax) AS totpax
FROM atelier ORDER BY " + Order_by + " " + SortDir + " LIMIT #Myid," +
PublicVariables.MySqlLimit, conn)
This gives an error here
_listBox[1].Items.Add(Convert.ToDateTime(reader["MyDate"]).ToString("d"));
Because there is NO ROWS int the table. Table is EMPTY.
But when I supress SUM(prix*pax) AS somme and SUM(pax) AS totpax from the query, reader does not read and no error occurs.
Is there any trick of MySql in there ?
I resolved the probleme by checking the table if there is any rows before calling this method but it's not what I like any idea ?
Use Group by clause for all non aggregate function before order by clause:
group by id,MyDate,nom,pax

MySQL, Concatenate two columns

There are two columns in a MySQL table: SUBJECT and YEAR.
I want to generate an alphanumeric unique number which holds the concatenated data from SUBJECT and YEAR.
How can I do this? Is it possible to use a simple operator like +?
You can use the CONCAT function like this:
SELECT CONCAT(`SUBJECT`, ' ', `YEAR`) FROM `table`
Update:
To get that result you can try this:
SET #rn := 0;
SELECT CONCAT(`SUBJECT`,'-',`YEAR`,'-',LPAD(#rn := #rn+1,3,'0'))
FROM `table`
You can use mysql built in CONCAT() for this.
SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;
change field name as your requirement
then the result is
and if you want to concat same field using other field which same then
SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1
then this is output
In php, we have two option to concatenate table columns.
First Option using Query
In query, CONCAT keyword used to concatenate two columns
SELECT CONCAT(`SUBJECT`,'_', `YEAR`) AS subject_year FROM `table_name`;
Second Option using symbol ( . )
After fetch the data from database table, assign the values to variable, then using ( . ) Symbol and concatenate the values
$subject = $row['SUBJECT'];
$year = $row['YEAR'];
$subject_year = $subject . "_" . $year;
Instead of underscore( _ ) , we will use the spaces, comma, letters,numbers..etc
In query, CONCAT_WS() function.
This function not only add multiple string values and makes them a single string value. It also let you define separator ( ” “, ” , “, ” – “,” _ “, etc.).
Syntax –
CONCAT_WS( SEPERATOR, column1, column2, ... )
Example
SELECT
topic,
CONCAT_WS( " ", subject, year ) AS subject_year
FROM table
I have two columns:
prenom and nom so to concatenate into a column with name chauffeur_sortant I used this script:
SELECT date as depart, retour, duree_mission, duree_utilisation, difference, observation, concat( tb_chaufeur_sortant.prenom, ' ', tb_chaufeur_sortant.nom) as chauffeur_sortant, concat(tb_chaufeur_entrant.prenom, ' ', tb_chaufeur_entrant.nom) as chauffeur_entrant
FROM tb_passation
INNER JOIN tb_vehicule
ON tb_vehicule.id = tb_passation.id_vehicule
INNER JOIN tb_chaufeur_sortant
ON tb_chaufeur_sortant.id = tb_passation.id_sortant
INNER JOIN tb_chaufeur_entrant
ON tb_chaufeur_entrant.id = tb_passation.id_entrant WHERE tb_vehicule.id = '';
$crud->set_relation('id','students','{first_name} {last_name}');
$crud->display_as('student_id','Students Name');

SQL table accepting same names again and again database name checking

I am trying to insert the guestpass type name in table guestpasstypes and at a time it will check the database whether the database has already that name or not by using this statement:
#"INSERT INTO guestpasstypes(guestPasstype_Name)values('" + tbPassType.Text + "') where not exists (select 'guestPasstype_Name' from guestpasstypes where guestPasstype_Name = '" + tbPassType.Text + "')"
but it accepts the duplicate name too, and it does not work. Would anyone please help on this?
For SQL Server it would look like this.
insert into guestpasstypes (guestPasstype_Name)
select 'name1'
where not exists (select *
from guestpasstypes
where guestPasstype_Name = 'name1')
I think it should work for MySQL as well.
If you are on SQL Server 2008 you can use MERGE.
merge guestpasstypes as G
using (select 'name2') as S(Name)
on G.guestPasstype_Name = S.Name
when not matched then
insert (guestPasstype_Name) values (Name);
UPDATE
I think the first option could be applied to your problem like this:
#"INSERT INTO guestpasstypes(guestPasstype_Name) select '" + tbPassType.Text
+ "' where not exists (select * from guestpasstypes where guestPasstype_Name = '"
+ tbPassType.Text + "')"
If you want it to throw an error you can either :
Put a unique index on the column (the easiest and preferred way)
or
Write a stored procedure which returns an error flag. Within the procedure, you first check for a matching value and if one is found, set the error flag and return. Otherwise do the insert as normal.
Try either INSERT IGNORE or INSERT ON DUPLICATE KEY:
INSERT IGNORE INTO `guestpasstypes`(`guestPasstype_Name`) values('" + tbPassType.Text + "');
OR
INSERT INTO `guestpasstypes`(`guestPasstype_Name`)values('" + tbPassType.Text + "') ON DUPLICATE KEY UPDATE `guestPasstype_Name` = `guestPasstype_Name`;