SQL run command if row exists - mysql

I'm new to MySQL and I'm trying to make the following pseudocode work:
SELECT IF(
EXISTS(SELECT * FROM users WHERE `email`="admin" AND `token`="blablabla"),
(UPDATE * FROM sometable WHERE `var`="notimportant"),
"NOT_AUTHORIZED");
What I'm trying to achieve is running code based on the presence of a row, and if it doesn't exists return a message, or something usable. If it does exists, run another SQL command instead, and return those results.
Is this possible?

Your intent is a bit hard to follow from the invalid syntax. But the gist of your question is that you can use a where clause:
UPDATE sometable
SET . . .
WHERE var = 'notimportant' AND
EXISTS (SELECT 1 FROM users WHERE email = 'admin' AND token = 'blablabla');
You can also represent this as a JOIN. Assuming the subquery returns at most one row:
UPDATE sometable t CROSS JOIN
(SELECT 1
FROM users
WHERE email = 'admin' AND token = 'blablabla'
LIMIT 1
) x
SET . . .
WHERE var = 'notimportant' ;

Related

Query blocking entirely MySQL server

I try to a run a specific query. However, when I execute it, the MySQL server doesn't respond anymore.
There is approximately 30000 rows in the table base_contrats_actifs but I don't know if this is a problem.
Here is the query :
UPDATE
base_contrats_actifs a
SET
a.code_indice = (
SELECT
MAX(g.code_indice)
FROM
base_gid g
WHERE
a.num_version = g.num_version_contrat
),
a.flag_bailleur_locataire = (
SELECT
MAX(g.flag_bailleur_locataire)
FROM
base_gid g
WHERE
a.num_version = g.num_version_contrat
),
a.compte_client = (
SELECT
MAX(g.compte_client)
FROM
base_gid g
WHERE
a.num_version = g.num_version_contrat
)
Can you see if there is an error ? If not, is there any way to debug the query ?
I don't know exactly why your update is non performant, but given the number of correlated subqueries you have, I'm not surprised. Try rewriting it as an update join:
UPDATE base_contrats_actifs a
INNER JOIN
(
SELECT
num_version_contrat,
MAX(code_indice) AS max_code_indice,
MAX(flag_bailleur_locataire) AS max_flag_bailleur_locataire,
MAX(compte_client) AS max_compte_client
FROM base_gid
GROUP BY num_version_contrat
) g
ON a.num_version = g.num_version_contrat
SET
a.code_indice = g.max_code_indice,
a.flag_bailleur_locataire = g.max_flag_bailleur_locataire,
a.compte_client = g.max_compte_client;

Using IF And Executing A Query If It's True

I have a query that i want it to be executed in a condition, for instance the api key .
Human :
If Api key is in the Api database, do the following query, say 'You Are Not Allowed' .
What i tried :
Select IF ( api.key = 'myapikey' , TrueQuery , 'You are not allowed') from api
My problem is in the query, i'm getting a lot of errors, the query contains " SELECT ... FROM ... WHERE ... GROUP BY ... LEFT JOIN " .
What's the way to accomplish it ?
Following example returns null :
SELECT CASE WHEN (SELECT api.app FROM api WHERE api.app = 'Test' )
THEN (SELECT items.rom_id FROM items)
END
Try this, without using IF, but using EXISTS.
select *
from ( TrueQuery ) t
where exists(select 1 from api where api.key = 'myapikey')

Complex UPDATE query in SQL Server 2008, rewrite from Oracle 10g

I need to re-write the following Oracle 10g query to work in SQL Server 2008
It's an update query, where some field are retrieved from a SELECT and some are given (from code).
UPDATE "BMAN_SQL"."CELLS_GLIST"
SET ("GLIST_ID", "GLIST_VALUE_ID") = (
SELECT "GLIST_ID", "GLIST_VAL_ID"
FROM "BMAN_SQL"."GLISTS_VAL_UOR"
WHERE ("UOR_ID"=3)
AND ("GLIST_CODE"='X')
),
"SESSION_ID" = 1553245736,
"USER_ID" = 13
WHERE EXISTS ( SELECT * FROM ... )
Note that I need to use the UPDATE SET ... WHERE EXIST ... structure for compatibility with Oracle (query are automatically built by a QueryBuilder class for each specific DBMS).
I also cannot write:
UPDATE "BMAN_SQL"."CELLS_GLIST"
SET ("GLIST_ID", "GLIST_VALUE_ID", "SESSION_ID", "USER_ID") = (
SELECT "GLIST_ID", "GLIST_VAL_ID", 1553245736, 13
FROM "BMAN_SQL"."GLISTS_VAL_UOR"
WHERE ("UOR_ID"=3)
AND ("GLIST_CODE"='X')
)
WHERE EXISTS ( SELECT * FROM ... )
because (as per this old thread Oracle "Cannot update to NULL") it returns an error if the SELECT does not fetch any record.
Thanks in advance!
You need to join update query in this case. Please see syntax below. <Your condition here> Replace this section with your join condition here.
UPDATE m
SET
GLIST_ID = r.GLIST_ID
,GLIST_VALUE_ID = r.GLIST_VAL_ID
, SESSION_ID= 1553245736
, USER_ID = 13
from BMAN_SQL.CELLS_GLIST m
inner join BMAN_SQL.GLISTS_VAL_UOR r on <Your condition here>
WHERE
r.UOR_ID=3 AND (r.GLIST_CODE='X') AND
EXISTS ( SELECT * FROM ... )
EDIT
UPDATE BMAN_SQL.CELLS_GLIST
SET
GLIST_ID = (SELECT TOP 1 GLIST_ID FROM BMAN_SQL.GLISTS_VAL_UOR WHERE (UOR_ID=3) AND (GLIST_CODE='X'))
,GLIST_VALUE_ID = (SELECT TOP 1 GLIST_VAL_ID FROM BMAN_SQL.GLISTS_VAL_UOR WHERE (UOR_ID=3) AND (GLIST_CODE='X'))
,SESSION_ID = 1553245736
,USER_ID = 13
WHERE EXISTS ( SELECT * FROM ... )

Merge not inserting. No error

Can someone tell me why this insert is failing but not giving me an error either? How do I fix this?
merge table1 as T1
using(select p.1,p.2,p.3,p.4,p.5 from #parameters p
inner join table1 t2
on p.1 = t2.1
and p.2 = t2.2
and p.3 = t2.3
and p.4 = t2.4) as SRC on SRC.2 = T1.2
when not matched then insert (p.1,p.2,p.3,p.4,p.5)
values (SRC.1,SRC.2,SRC.3,SRC.4,SRC.5)
when matched then update set t1.5 = SRC.5;
The T1 table is currently empty so nothing can match. The parameters table does have data in it. I simply need to modify this merge so that it checks all 4 fields before deciding what to do.
You can't select from a variable: from #parameters
See the following post: Using a variable for table name in 'From' clause in SQL Server 2008
Actually, you can use a variable table. Check it out:
MERGE Target_table AS [Target]
USING #parameters AS [Source]
ON (
[Target].col1 = [Source].col1
AND [Target].col2 = [Source].col2
AND [Target].col3 = [Source].col3
AND [Target].col4 = [Source].col4
)
WHEN NOT MATCHED BY TARGET
THEN INSERT (col1,col2,col3,col4,col5)
VALUES (
[Source].col1
,[Source].col2
,[Source].col3
,[Source].col4
,[Source].col5
)
WHEN MATCHED
THEN UPDATE SET [Target].col5 = [Source].col5;

IF condition in mysql

I have a contact table I wish to query when a certain condition exists. I tried the query below but am getting a syntax error.
SELECT *
FROM contact_details
WHERE contactDeleted` =0
AND IF ( contactVisibility = "private"
, SELECT * FROM contact_details
WHERE contactUserId = 1
, IF( contactVisibility = "group"
, SELECT * FROM contact_details
WHERE contactGroup = 3
)
)
If I'm understanding your question correctly (which is difficult with the lack of info you've provided. Sample datasets and expected outcomes are typically helpful), then I don't believe you need IFs at all for what you want. The following will return contacts that are not deleted and who either have (visibility = "private" and userId = 1) OR (visibility = "group" and group = 3)
SELECT *
FROM contact_details
WHERE contactDeleted = 0
AND (
(contactVisibility = "public")
OR
(contactVisibility = "private" AND contactUserId = 1)
OR
(contactVisibility = "group" AND contactGroup = 3)
)
I am assuming you want to use the IF() function and not the statement which is for stored functions..
Refer to this link for more information on that.
Notice that you have put 2 select statements in there, where the custom return values are supposed to be. So you are returning a SELECT *... now notice that in your upper level sql statement you have an AND.. so you basically writing AND SELECT *.. which will give you the syntax error.
Try using .. AND x IN (SELECT *) .. to find if x is in the returned values.
Let me also list this link to make use of an existing and well written answer which may also applicable to your question.