I have 2 tables: users with columns (id,username, password), and user_failed with columns (user_id, failed, time). is there any possible way i can insert into table user_failed by only using username? i try this code but it failed:
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
VALUES (SELECT user_id FROM users WHERE username = 'pokemon','',3)
Your SQL query is incorrect for several reasons.
The following should work if I have interpreted your query correctly.
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
SELECT id, '', 3 FROM users WHERE username = 'pokemon'
INSERTing into a table from a SELECT does not require VALUES ( ... ). Here is an example of how you would use VALUES ( ... ):
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
VALUES (1, '', 3)
Also, your sub query SELECT user_id FROM users WHERE username = 'pokemon','',3 the WHERE clause is invalid. Specifically the '',3 part which I assume is the values you wanted to insert for time and failed.
This will work....you have to add plain parentheses before and after statements.
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`) VALUES ((SELECT user_id FROM users WHERE username = 'pokemon'),'',3)
Related
I have two tables which are user and info. Need to insert into info table with max id from user table.I tried using below query with single row insert it was working fine. But I try to multiple insert it doesn't. getting error as "#1241 - Operand should contain 1 column(s)"
INSERT INTO user( name, email, password )
values
(
((SELECT MAX( id ) as id from info), 'test1#gmail.com', '123'),
((SELECT MAX( id ) as id from info), 'test1#gmail.com', '123'))
When inserting from a select, we don't need to use VALUES:
INSERT INTO user( name, email, password )
SELECT MAX(id), 'test1#gmail.com', '123' FROM info
UNION ALL
SELECT MAX(id), 'test1#gmail.com', '123' FROM info;
Note also that you probably don't need to wrap the MAX(id) query as a subquery. Instead, just select the constants you want in a single top level query.
I want to make a insert into 2 tables
visits:
visit_id int | card_id int
registration:
registration_id int | type enum('in','out') | timestamp int | visit_id int
I want something like:
INSERT INTO `visits` as v ,`registration` as v
(v.`visit_id`,v.`card_id`,r.`registration_id`, r.`type`, r.`timestamp`, r.`visit_id`)
VALUES (NULL, 12131141,NULL, UNIX_TIMESTAMP(), v.`visit_id`);
I wonder if its possible
It's not possible with one query as INSERT can only insert data to one table in mysql. You can either
write this as two queries and execute them as a batch
create a stored procedure that would execute two insert command
You can wrap those inserts in transaction if you need to make sure that both queries will write the data.
It seems like the problem you are trying to solve is to get the auto-increment value from the "visits" row to insert into "registration". Am I right?
If so, you can just use the LAST_INSERT_ID() function like this:
INSERT INTO `visits` (`visit_id`,`card_id`)
VALUES (NULL, 12131141);
INSERT INTO `registration` (`registration_id`, `type`, `timestamp`, `visit_id`)
VALUES (NULL, 'in', UNIX_TIMESTAMP(), LAST_INSERT_ID());
You can always do something like this
INSERT IGNORE INTO `table2` VALUES ((select id from table1 where col="value"), 3, 4, 5)
INSERT INTO designation as de,
department as da,
profile as pr
(designation_name,
depart_id,
id,
username,
department,
designation)
select de.designation_name,
de.depart_id,da.id,
pr.username,
pr.department,
pr.designation
from
designation,
department,
profile
de.designation_name='project manager' AND de.id='1' OR
de.depart_id='2' AND de.id='2' OR
da.id='2' OR
pr.username='kapil.purohit' AND pr.id='9' AND pr.status='1' OR
pr.department='1' AND pr.id='9' OR
pr.designation='3' AND pr.id='9' AND pr.status='1'
WHERE
de.id = da.id AND
da.id = pr.id AND
de.id = pr.id AND
ORDER BY de.id DESC
I want to insert values to a row in my customer table if the Name value I'm providing do not already exist,
After some searching I used this sql query to do it and it does not work :(
IF NOT EXISTS (SELECT Name FROM customer WHERE Name = 'Riyafa')
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
VALUES ('Riyafa', 'ABC', '555','1000');
Please instruct me why that is incorrect.
The if statement is only allowed in stored procedures, functions, and triggers. One way you can do this is:
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
SELECT name, address, contactno, total_amount
FROM (SELECT 'Riyafa' as name, 'ABC' as address, '555' as contact no, '1000' as total_amount) t
WHERE NOT EXISTS (SELECT 1 FROM customer c WHERE c.name = t.name);
A better approach, however, is to have the database enforce uniqueness on the name. Start by creating a unique index or name:
CREATE UNIQUE INDEX idx_customer_name ON customer(name);
Then use a construct such as on duplicate key update:
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
SELECT 'Riyafa' as name, 'ABC' as address, '555' as contact no, '1000' as total_amount
ON DUPLICATE KEY UPDATE Name = VALUES(Name);
The expression ON DUPLICATE KEY UPDATE Name = VALUES(Name) actually doesn't do anything, but it prevents the INSERT from returning an error.
i want to insert the scholar's id to the tblinbox. Here is my query:
$sql = "INSERT INTO tblinbox VALUES ('','$sender','$type','$subject','$LRN','$content','$date', '$newyearLevel','','$userType','THIS_IS_FOR_THE_ID_OF_THE_SCHOLAR')
SELECT id FROM tblscholar WHERE schoYear = '$newyearLevel'";
my problem is,it is not inserting. what will i change in my query?
INSERT ... SELECT syntax does not allow for VALUES declaration. The values ARE the results returned from the SELECT.
See the documentation here: http://dev.mysql.com/doc/refman/5.6/en/insert-select.html
I honestly am not fully sure what you are trying to do with your insert. If you are trying to insert the same values held in your variables for each id value from the tblscholar table then perhaps you need to do something like this:
INSERT INTO tblinbox
/*
maybe add column definitions here to make it clearer
column definitions could look like this:
(
someField,
type,
subject,
LRN,
content,
`date`,
newyearLevel,
someOtherField,
userType,
id
)
*/
SELECT
'',
'$sender',
'$type',
'$subject',
'$LRN',
'$content',
'$date',
'$newyearLevel',
'',
'$userType',
id
FROM tblscholar
WHERE schoYear = '$newyearLevel'
An INSERT statement supports either a VALUES clause followed by a row of values, or else a SELECT query with columns to match the columns of the table you want to insert into.
But not both!
But you can add constant values into your SELECT query:
$sql = "INSERT INTO tblinbox
SELECT '','$sender','$type','$subject','$LRN','$content','$date',
'$newyearLevel','','$userType', id
FROM tblscholar WHERE schoYear = '$newyearLevel'";
considering id is the first column in your insert statement, try this
$sql = "INSERT INTO tblinbox VALUES ((SELECT id FROM tblscholar WHERE schoYear = '$newyearLevel'),'$sender','$type','$subject','$LRN','$content','$date', '$newyearLevel','','$userType')";
You can insert values either fetching values form another table or providing values as follows:
Way 1:
INSERT INTO tblinbox(coloumn_name1,coloumn_name2) VALUES (value1,value2);
Way 2:
INSERT INTO tblinbox(coloumn_name1,coloumn_name2) SELECT value1,value2 from tblscholer where schoYear= '$newyearLevel';
I have a task to update existing multiple product-related tables with new entries if product name doesn't exist (no update). Thing is that this is one time action so product name column is not and will not be set as unique, primary, etc (and it is not possible for me to change it anyway).
I would be delighted if i could access the database remotely and use PHP, but due to security reasons i have access only to PhpMyAdmin on that server.
After googling for couple of hours i realized that either all results are about single INSERT IGNORE or similar constructions, or they are too complicated for me non-mysql brain to understand or solutions just won't work (like IF statement throws syntax error on that 5.5.8 MySQL server.
So thing is - there are 7 tables with all kinds of information on product (product, variant, image, category, product relation to category, prices, discounts). I have to check if product name doesn't exist and if true then insert new entries in all 7 tables. Additionaly i should create new product category entry if such doesn't exist (again, by name, not id)
In my humble opinion it would be like this:
IF (SELECT ProductName from `product` where ProductName='Pony') IS NULL THEN
INSERT INTO `product` VALUES ('', 'Pony');
#productId = (SELECT LAST_INSERT_ID());
INSERT INTO `category` (Name) SELECT 'Everything Nice' FROM `category` WHERE NOT EXISTS (SELECT Name FROM `category` WHERE Name='Everything Nice') LIMIT 1;
SET #categoryId = (SELECT CategoryId FROM `category` WHERE Name='Everything Nice');
INSERT INTO `product_rel_category` VALUES (#productId, #categoryId);
INSERT INTO `variant` VALUES ('', 'Nice');
#variantId = (SELECT LAST_INSERT_ID());
INSERT INTO `product_rel_variant` VALUES (#productId, #variantId);
INSERT INTO `variant` VALUES ('', 'Sweet');
#variantId = (SELECT LAST_INSERT_ID());
INSERT INTO `product_rel_variant` VALUES (#productId, #variantId);
INSERT INTO `variant` VALUES ('', 'Pink');
#variantId = (SELECT LAST_INSERT_ID());
INSERT INTO `product_rel_variant` VALUES (#productId, #variantId);
... etc ...
ENDIF;
MySQL yells about syntax on IF in such query. I also tried working all kinds of procedures, but since I know only 'insert, update, select, delete', there is nothing much i can compose now.
So do you have an advise on solution on how i can make multiple INSERT/SELECT queries if a value in one table doesn't exist.
Sincerely thanks.