MySQL IF/ELSE statements in WHERE - mysql

I want to look for duplicate members in the database.
First I want to check if their username exists.
If not, I want to check their first name, last name and email address.
Lastly if that doesn't match anyone, I want to just check if a first name and last name exists.
I've been looking at IF/ELSE statements and even CASE in Google but I can't seem to figure out how it would work in my situation.
Here's some code that in my mind makes sense (being a PHP programmer) but it isn't how MySQL does things...
SELECT id FROM members WHERE (
IF (member_username = 'john.doe')
ELSEIF (member_firstname = 'John' AND member_lastname = 'Doe' AND member_email = 'john#doe.com')
ELSE (member_firstname = 'John' AND member_lastname = 'Doe')
) AND deleted = 0
How would I translate the above into working MySQL code if it's even possible.

I ended up taking #Corbin's advice and used
SELECT username, first_name, last_name, email_addr FROM members WHERE username = 'username' OR (first_name = 'first name' AND last_name = 'last name')
And then used PHP if/else statements to determine which record was the exact duplicate.

What would be wrong with this?
SELECT id
FROM members
WHERE (member_username = 'john.doe'
OR (member_firstname = 'John' AND member_lastname = 'Doe' AND member_email = 'john#doe.com')
OR (member_firstname = 'John' AND member_lastname = 'Do'))
AND deleted = 0

Have a look at this: http://docs.oracle.com/cd/E17952_01/refman-5.5-en/control-flow-functions.html#operator_case

Don't forget TOP 1!
SELECT TOP 1 id FROM members WHERE deleted = 0 AND
(
(member_username = 'john.doe') OR
(member_email = 'john#doe.com' AND member_firstname = 'John' AND member_lastname = 'Doe') OR
(member_firstname = 'John' AND member_lastname = 'Doe')
)

Related

Why UPDATE query not working

Here is my code
UPDATE project SET name = 'New Name' AND platform = 'iOS' WHERE id = 2
When I process it via phpMyAdmin, it is changing the name to 0. When I rerun the query, it says 0 rows affected. When I change back the name to something else and rerun the query, it says 1 row affected, but changing the name back to 0 and nothing else.
What am I doing wrong?
I have the table with proper structure and have a record with id=2
Remove AND and use , instead
UPDATE project SET name = 'New Name', platform = 'iOS' WHERE id = 2
Your UPDATE syntax is wrong. It should be this:
UPDATE project SET name = 'New Name', platform = 'iOS' WHERE id = 2
MySQL is changing name to 0 because it is confused about what you mean by AND. It's possible MySQL is interpreting that statement to be a logical expression, which gets converted into a 1 for TRUE or a 0 for FALSE (in this case, the latter).
Think of your original query like this, with parentheses used to illustrate operator precedence:
UPDATE project SET name = ('New Name' AND (platform = 'iOS')) WHERE id = 2
UPDATE project SET name = 'New Name', platform = 'iOS' WHERE id = 2
Depending on what you want to do, correct syntax is
UPDATE project SET name = 'New Name', platform = 'iOS' WHERE id = 2;
Or
UPDATE project SET name = 'New Name' WHERE id = 2 AND platform = 'IOS';

query sql table By First_Name and/or Last_Name

I need to write a query that query customer table base on first_name and/ or last_name. in my query it works for example when I run with firstname =Ann it brings all the customers with that firstname and when I run with lastname=sam brings all will that last name, but when I run with 'Ann','Sam' instead of bring only one record that is match this it brings all with firstname Ann or last same sam so it bring several records.
select * from customer
where WHERE --(CONVERT(varchar(50),decryptbykey([Account_Number]))=
#UserName or ce.Email= #UserName or Username=#UserName )
((CONVERT(varchar(50),decryptbykey([First_Name]))) =#First_Name)
and (CONVERT(varchar(50),decryptbykey([Last_Name])) =#Last_Name)
or ((CONVERT(varchar(50),decryptbykey([First_Name]))) =#First_Name)
or (CONVERT(varchar(50),decryptbykey([Last_Name])) =#Last_Name)
In this scenario I'd treat each parameter as optional. If provided then enforce the condition, otherwise skip that check. This type of query is convenient in the sense that you do not have to maintain n! versions of your query, however I must warn you this is prone to bad cached query plans.
If you experience a significant slowdown that you cannot explain you might want to tack 'OPTION (RECOMPILE)' to the end of you query. In general this may seem like a bad idea but I'd rather SQL server take an extra 5 ms each query than take 30 seconds once. Locks, database load, user experience, etc. As usual, forcing query options is generally a bad idea and should only be done if there is no other reasonable solution.
IF (#UserName_Name = '')
SET #First_Name = NULL;
IF (#First_Name = '')
SET #First_Name = NULL;
IF (#Last_Name = '')
SET #First_Name = NULL;
select *
from customer
where (#UserName IS NULL
OR Username = #UserName
OR Email = #UserName
OR CONVERT(varchar(50), decryptbykey([Account_Number])) = #UserName)
AND (#First_Name IS NULL OR CONVERT(varchar(50), decryptbykey([First_Name])) = #First_Name)
AND (#Last_Name IS NULL OR CONVERT(varchar(50), decryptbykey([First_Name])) = #Last_Name);
This might not be pretty, but it works as you describe it.
If exact match on both Firstname AND Lastname only the exact match is returned (could be more than one though). If match on only Firstname OR Lastname, all matching records are returned
SELECT * FROM customer
WHERE
(
(First_name = (CASE WHEN (First_name = #First_Name AND Last_name = #Last_Name) THEN #First_Name END))
AND
(Last_name = (CASE WHEN (First_name = #First_Name AND Last_name = #Last_Name) THEN #Last_Name END))
)
OR
(
(First_name = (CASE WHEN (First_name = #First_Name AND Last_name <> #Last_Name) THEN #First_Name END))
OR
(Last_name = (CASE WHEN (First_name <> #First_Name AND Last_name = #Last_Name) THEN #Last_Name END))
)
You'll have to add your other filters and CONVERTs yourself.

UPDATE multiple rows with different values in one query in MySQL

I am trying to understand how to UPDATE multiple rows with different values and I just don't get it. The solution is everywhere but to me it looks difficult to understand.
For instance, three updates into 1 query:
UPDATE table_users
SET cod_user = '622057'
, date = '12082014'
WHERE user_rol = 'student'
AND cod_office = '17389551';
UPDATE table_users
SET cod_user = '2913659'
, date = '12082014'
WHERE user_rol = 'assistant'
AND cod_office = '17389551';
UPDATE table_users
SET cod_user = '6160230'
, date = '12082014'
WHERE user_rol = 'admin'
AND cod_office = '17389551';
I read an example, but I really don't understand how to make the query. i.e:
UPDATE table_to_update
SET cod_user= IF(cod_office = '17389551','622057','2913659','6160230')
,date = IF(cod_office = '17389551','12082014')
WHERE ?? IN (??) ;
I'm not entirely clear how to do the query if there are multiple condition in the WHERE and in the IF condition..any ideas?
You can do it this way:
UPDATE table_users
SET cod_user = (case when user_role = 'student' then '622057'
when user_role = 'assistant' then '2913659'
when user_role = 'admin' then '6160230'
end),
date = '12082014'
WHERE user_role in ('student', 'assistant', 'admin') AND
cod_office = '17389551';
I don't understand your date format. Dates should be stored in the database using native date and time types.
MySQL allows a more readable way to combine multiple updates into a single query. This seems to better fit the scenario you describe, is much easier to read, and avoids those difficult-to-untangle multiple conditions.
INSERT INTO table_users (cod_user, date, user_rol, cod_office)
VALUES
('622057', '12082014', 'student', '17389551'),
('2913659', '12082014', 'assistant','17389551'),
('6160230', '12082014', 'admin', '17389551')
ON DUPLICATE KEY UPDATE
cod_user=VALUES(cod_user), date=VALUES(date)
This assumes that the user_rol, cod_office combination is a primary key. If only one of these is the primary key, then add the other field to the UPDATE list.
If neither of them is a primary key (that seems unlikely) then this approach will always create new records - probably not what is wanted.
However, this approach makes prepared statements easier to build and more concise.
UPDATE table_name
SET cod_user =
CASE
WHEN user_rol = 'student' THEN '622057'
WHEN user_rol = 'assistant' THEN '2913659'
WHEN user_rol = 'admin' THEN '6160230'
END, date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';
You can use a CASE statement to handle multiple if/then scenarios:
UPDATE table_to_update
SET cod_user= CASE WHEN user_rol = 'student' THEN '622057'
WHEN user_rol = 'assistant' THEN '2913659'
WHEN user_rol = 'admin' THEN '6160230'
END
,date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';
To Extend on #Trevedhek answer,
In case the update has to be done with non-unique keys, 4 queries will be need
NOTE: This is not transaction-safe
This can be done using a temp table.
Step 1: Create a temp table keys and the columns you want to update
CREATE TEMPORARY TABLE temp_table_users
(
cod_user varchar(50)
, date varchar(50)
, user_rol varchar(50)
, cod_office varchar(50)
) ENGINE=MEMORY
Step 2: Insert the values into the temp table
Step 3: Update the original table
UPDATE table_users t1
JOIN temp_table_users tt1 using(user_rol,cod_office)
SET
t1.cod_office = tt1.cod_office
t1.date = tt1.date
Step 4: Drop the temp table
In php, you use multi_query method of mysqli instance.
$sql = "SELECT COUNT(*) AS _num FROM test;
INSERT INTO test(id) VALUES (1);
SELECT COUNT(*) AS _num FROM test; ";
$mysqli->multi_query($sql);
comparing result to transaction, insert, case methods in update 30,000 raw.
Transaction: 5.5194580554962
Insert: 0.20669293403625
Case: 16.474853992462
Multi: 0.0412278175354
As you can see, multiple statements query is more efficient than the highest answer.
Just in case if you get error message like this:
PHP Warning: Error while sending SET_OPTION packet
You may need to increase the max_allowed_packet in mysql config file.
UPDATE Table1 SET col1= col2 FROM (SELECT col2, col3 FROM Table2) as newTbl WHERE col4= col3
Here col4 & col1 are in Table1. col2 & col3 are in Table2 I Am trying to update each col1 where col4 = col3 different value for each row
I did it this way:
<update id="updateSettings" parameterType="PushSettings">
<foreach collection="settings" item="setting">
UPDATE push_setting SET status = #{setting.status}
WHERE type = #{setting.type} AND user_id = #{userId};
</foreach>
</update>
where PushSettings is
public class PushSettings {
private List<PushSetting> settings;
private String userId;
}
it works fine

Zend Framework - and in where clause

I am working on Zend Framework, got 1 problem in query, i want to fetch userid from tbl_user & want to check record with And in where clause
here is my query
$sql=$this->select()->from(users)->where('email = ? ', trim($email) , 'password = ?', md5(trim($password)) );
when i am printing query it prints
select * from users where email = 'test#gmail.com';
i want to print query like
select * from users where email = 'test#gmail.com' AND password='123456';
thanks in advance
You were close. You just need to call the where() method twice:
$this->select()->from(users)->where('email = ?', trim($email))
->where('password = ?', md5(trim($password)));

MySQL UPDATE only if field in other table meets condition

I am having a little trouble trying to accomplish this. Here is the gist of what I need to do:
UPDATE links SET
link = '$link', rid = $rid, order = $order
WHERE lid = $lid
IF (SELECT COUNT(*) FROM resources WHERE rid = $rid AND (sid = $sid OR sid IS NULL) AND types IS NULL) == 1;
So basically, I want to run the UPDATE if and only if the resource in the resources table is associated with the site (sid) or is not associated with any particular site and types is null.
I suppose I can run a PHP conditional, but it would be preferable if I could do this with one query. Is it possible?
Thansk so much in advance!
UPDATE links
SET link = '$link', rid = $rid, order = $order
WHERE lid = $lid
and (SELECT COUNT(*)
FROM resources
WHERE rid = $rid
AND (sid = $sid OR sid IS NULL)
AND types IS NULL) = 1;