MySQL INSERT if SELECT COUNT(*) is greater than 1 - mysql

I'm trying a MySQL statement, where I need to check of the user credentials are correct; and only if they are correct -- I insert the data
IF (SELECT COUNT(*) FROM users WHERE uid = 1 AND password = "67^8ax%!") > 0
THEN
INSERT INTO messages (uid, text, time)
VALUES (1, "Hello", CURRENT_TIMESTAMP)
END IF
I have to do both the operations in a single MySQL query due the limitations of my platform.
Any way to get this working?

Try this query
Working in MYSQL, thought shouldn't work in MYSQL :P
INSERT INTO messages (uid, text, time)
(SELECT 1, "Hello", CURRENT_TIMESTAMP FROM users WHERE uid = 1 AND password = "67^8ax%!")
Will work if there is only 1 distinct user with the given username and password..
FIDDLE

Related

INSERT value using SELECT in mysql

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)

MySQL limit maximum rows for same "user" value

How can I limit in MySQL maximum rows for the same "user" value?
For example, I have table with columns
id | user | data
and I would like to limit maximum rows count to 5 for each user (the same "user" value).
My idea is to use transactions (InnoDB):
start transaction
insert row with user = "XXX"
count rows, where user = "XXX"
if count < 5 commit else rollback
Is my idea good or exist also another (better) solution?
I think that it's ok, You may want to make a
select count(1) from table where user='XXX'
and check the count before performing the insert.
This could be done by using special "dual" table:
INSERT INTO table (id, user, data)
SELECT 1, 'XXX', 'somedata'
FROM dual
WHERE NOT EXISTS (
SELECT user
FROM t
WHERE user = 'XXX'
GROUP BY user
HAVING COUNT(*) >= 5
)

SQL Error when trying to insert one value into one row for a column

I'm using MySQL 5.7 and for some reason my INSERT statement isn't working as before even though the syntax looks correct. It's error-ing out on the where statement...
SQL:
insert into users(age) values('16') where username='r';
If the row for username r already exists perhaps you are looking to update the age value instead?
Use: update users set age = 16 where username = 'r' instead.
Also, I'm just guessing here, but maybe age holds a numeric value, and if so you can remove the quotes around 16.
That syntax isn't correct. You can't use where like that. Perhaps you want something like:
insert into users (username, age)
values ('r', '16')
http://dev.mysql.com/doc/refman/5.7/en/insert.html
Alternatively if that user already exists, you might be looking for an update statement instead:
update users set age = '16' where username = 'r'
INSERT statements must not contain a WHERE clause. Remove it.
If, in fact what you are trying to do is update an existing row, use an UPDATE statement, not an INSERT statement.
update users set age = '16' where username='r';
If you want to insert new records in your table, you have to write query for inserting data.
SQL INSERT INTO Statement syntax is this:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
In your case, if you don't have the record in your database, your query will look like this:
INSERT INTO users (username, age)
VALUES ('r', '16')
But if you want to update existing records in your table, you have to write query for updating data using the SQL UPDATE Statement.
The syntax for this is:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
To update the record/s, you have to specify clause in WHERE which record should be modified.
To modify age of user/s with username that is equals 'r', this is the query:
UPDATE users SET age = 16 WHERE username = 'r'
but if you want to modify for all users which usernames starts with 'r':
UPDATE users SET age = 16 WHERE username = 'r%'
I hope this explanation will help you to understand better SQL statements for INSERT new and UPDATE existing records.

How do I write a single SQL statement for MySQL that checks a value and then does INSERT if true?

I have the following statement:
SELECT pinpicsid
FROM user_collection
JOIN pin ON user_collection.pinid = pin.id
WHERE username = 'myuser'
AND pinpicsid = '98802';
If it returns blank (or no rows), I'd like to do an INSERT like this:
SELECT id INTO #id FROM pin WHERE pinpicsid = '98802';
INSERT INTO user_collection (pinid, username)
VALUES (#id, 'ethanwa');
Is there any possible way to combine all of these into one single statement?
Why not just INSERT...SELECT?
INSERT INTO user_collection (pinid, username)
SELECT id, 'ethanwa' FROM pin WHERE pinpicsid = '98802';
Syntax here: http://dev.mysql.com/doc/refman/5.6/en/insert-select.html
If you need to enforce the uniqueness of pinid, but still want to update the username, you can do this:
INSERT INTO user_collection (pinid, username)
SELECT id, 'ethanwa' FROM pin WHERE pinpicsid = '98802'
ON DUPLICATE KEY UPDATE username = VALUES(username)
Without knowing more about your goals for this script, it's hard to get much more precise.

Insert into a table, if there is no such rows

I have a sessions table with the 'userid' and 'expired' columns. I want to check, whether any row with the given user ID and not expired exists and insert a new row, if no rows found.
I've read about INSERT IGNORE, but (userid + expired) cannot be a key, since it's possible to have multiple rows with the same users (all expired), I cannot only have more than 1 not expired user.
I tried this, but to no avail ('You have an error...'):
IF (SELECT 1 FROM sessions WHERE user = :user AND expired = 0) <> 1
INSERT INTO sessions (user) VALUES(:user)
('expired' is 0 by default). mySQL version is 5.
UPDATE.
I've tried this as well:
IF NOT EXISTS(SELECT 1 FROM sessions WHERE user = 0 AND expired = 0)
INSERT INTO sessions (user) VALUES(0)
using HeidySQL 7. It doesn't work neither. mySQL version is 5.5.
UPDATE2. Logical errors in my statement fixed.
Regards,
use If exists clause (in this case, not exists)
IF NOT EXISTS(SELECT 1 FROM sessions WHERE user = 0 AND expired = 0)
INSERT INTO sessions (`user`) VALUES(:user)
edit
INSERT INTO sessions (`user`) select user from
(select :user as user from sessions where not exists(SELECT 1 FROM sessions WHERE user = 0 AND expired = 0)) T1
then put 0 or the value you want harcoded in :user
INSERT INTO sessions (`user`) select user from
(select 0 as user from sessions where not exists(SELECT 1 FROM sessions WHERE user = 0 AND expired = 0)) T1
Elvieejo's solution seems good, except looks like you'd have to use not exists going by the problem stated.
IF NOT EXISTS(SELECT 1 FROM sessions WHERE user = 0 AND expired = 0)
INSERT INTO sessions (user) VALUES(:user)
INSERT IGNORE INTO sessions (user) VALUES(:user)
The problem with my statement is that IF EXISTS is supposed to be in a stored procedure. Nevertheless, the function IF() works:
SELECT IF(EXISTS(SELECT 1 FROM sessions WHERE user = 0 AND expired = 0), 0, 1)
Now I'm looking for how to equal plain value like 0 and INSERT INTO statement. This doesn't work:
SELECT IF(EXISTS(SELECT 1 FROM sessions WHERE user = 0 AND expired = 0), 0,
INSERT INTO sessions (user) VALUES (0) SELECT)
If it was C++, I'd say 'type mismatch between ?: operands' and use comma operator. In SQL it doesn't work.
UPDATE
Well, I've just created a stored routine. Just because I cannot use IF otherwise. What a stupid RDBMS this mySQL is!