update query based on select query - mysql

exactly I want to write "UPDATE" and "SELECT" into one query.
I need check for setting a field.
for this action, I used SELECT query on TABLE1 and then if it dose not have result, another filed of TABLE2 is updated.
FOR EX:
$res = mysqli_query($con , "select sID FROM schedule where (dayID = '{$this->dID}' AND patientID = '')");
$rep = mysqli_fetch_array($res);
if(count($rep) == 0)
mysqli_query($con,"update days set schFilled = 1 where dID = '{$this->dID}'");
else
mysqli_query($con,"update days set schFilled = 0 where dID = '{$this->dID}'");
I would like run those with ONE query, in fact I want something like this:(whit CASE to write second update too)
update days set schFilled = 0 where( (select sID FROM schedule where (dayID = '{$this->dID}' AND patientID = '') IS NULL) AND (dID = '{$this->dID}'))

use the mysqli object like this:
$res = mysqli_query($con , "your select");
if($res->num_rows === 0) {
//no res
}
else {
//else
}

"UPDATE days SET schFilled =
CASE
WHEN (SELECT IF(EXISTS(select sID FROM schedule where (dayID = '{$this->dID}' AND patientID = '' AND hour != 0)), 1, 0))
THEN 0
ELSE 1
END
where dID = '{$this->dID}'"

Related

How to use IF() and ELSE () statements in MYSQL

I want to DELETE data OR UPDATE data in MYSQL. such that if column message_deleted_by is found in a string IN() then the query should delete rows where the WHERE clause(filtering) is true ELSE the query should update message_table column message_deleted_by with some data ....ALL IN THE SAME QUERY
if this can be achieved please help.
I'v tried and tried but it output errors.
$token = mysqli_real_escape_string($dbc_conn,encode64(getsecreteToken($_POST["token"])));
$mid = mysqli_real_escape_string($dbc_conn,$_POST["mid"]);
$rid = mysqli_real_escape_string($dbc_conn,$_POST["rid"]);
$sid = mysqli_real_escape_string($dbc_conn,$_POST["sid"]);
$group = implode(",",array($rid,$sid));
$IsLoggIn = '2';
$SQL = "
IF(
SELECT message_deleted_by AS mdb FROM $message_tatable
WHERE (
m.sender_id='$IsLoggIn' AND m.recipient_id='$rid'
) AND
m.token='$token' AND m.id='$mid'
) mdb IN($group) THEN
DELETE m,mf
FROM $message_tatable m
LEFT JOIN $message_files_tb mf ON
m.token=mf.token
WHERE (
m.sender_id='$IsLoggIn' AND m.recipient_id='$rid'
) AND
m.token='$token' AND m.id='$mid';
ELSE
UPDATE $message_tatable SET message_deleted_by='$IsLoggIn'
WHERE (
m.sender_id='$IsLoggIn' AND m.recipient_id='$rid'
) AND
m.token='$token' AND m.id='$mid';
END IF;
";
//QUERY database
$query = mysqli_query($dbc_conn,$SQL);
die(mysqli_error($dbc_conn));
Try this,
UPDATE $message_tatable m
LEFT JOIN $message_files_tb mf
ON m.token=mf.token
SET m=NULL,
mf=NULL
WHERE m OR mf=SELECT message_deleted_by FROM $message_tatable IN($group)
AND m.sender_id='$IsLoggIn' AND m.recipient_id='$rid'
AND m.token='$token' AND m.id='$mid'

error message not displaying on mysql stored procedure

I am trying to validate something but It always returns a success result. I wonder what's wrong with my codes.
INSERT INTO playlist_details (playlist_id,filename,image_id,transition,timeframe,userid,update_date)
VALUES (i_playlistid,i_filename,i_imageid, i_transition, i_time, i_userid,i_date);
SELECT booking_id INTO v_booking_id FROM staging_table WHERE playlist_id = i_playlistid LIMIT 1;
SELECT num_of_spots INTO v_spots FROM booking_sum WHERE booking_id = v_booking_id;
SET v_allowed_time = v_spots * 30;
IF ((SELECT SUM(timeframe) FROM playlist_details WHERE playlist_id = i_playlistid) > v_allowed_time) THEN
SET o_success = FALSE;
SET o_message = 'You exceeded the time allowed with your booking';
SELECT playlist_id,filename,image_id,transition,timeframe,userid FROM playlist_details
WHERE userid = i_userid;
ELSE
SELECT playlist_id,filename,image_id,transition,timeframe,userid FROM playlist_details
WHERE userid = i_userid;
SET o_success = TRUE;
SET o_message = 'Success';
END IF;

TSQL works in query analyzer but fails as a job step

I have a multi step job that has worked fine for months. All of the sudden it is failing on step 5. If I run the tsql for step 5 in query analyzer it works just fine. Any thoughts? Below is the code I am using.
MERGE BISS..tblBoxInfo AS target
USING ( SELECT BX.BOX_BOXNO, BX.BOX_UDF_AIRR_BOXNO, CONVERT(VARCHAR(510), BX.BOX_DESC),
--RTRIM(STUFF(CONVERT(VARCHAR(510),BOX_DESC), 1,
PATINDEX(N'%[^' + CHAR(9)+CHAR(10)+CHAR(13)+CHAR(32) + N']%', BOX_DESC)-1, N' '))
BX.BOX_UDF_NARA_LOCATION, CONVERT(VARCHAR(6),DP.DEPT_ID),
DP.DEPT_NAME, BX.BOX_UBN, BX.BOX_RCID, CONVERT(VARCHAR(15),CLV.CLV_TITLE),
BX.BOX_DT_CREATION,
CONVERT(VARCHAR(MAX), BX.BOX_UDF_TRIBES),--was NOS = CASE BOX_SROOM_INDEX WHEN 19 THEN 1 ELSE 0 END,
BX.BOX_DT_FROM, BX.BOX_DT_TO, SS.SROOM_ID
FROM ISTAbq3Ver01.VssEnt.dbo.BOXES BX
LEFT JOIN ISTAbq3Ver01.VssEnt.dbo.DEPTS DP
ON DP.DEPT_ID_FULL = BX.BOX_DEPT
LEFT JOIN ISTAbq3Ver01.VssEnt.dbo.SROOMS SS
ON SS.SROOM_AUTO_INDEX = BX.BOX_SROOM_INDEX
LEFT JOIN ISTAbq3Ver01.VssEnt.dbo.CUSTOM_LISTS_VALUES CLV
ON CLV.CLV_AUTO_INDEX = BX.BOX_UDF_AIRR_WORKSITE
WHERE NOT ( SS.SROOM_ID IN (
N'MP',
N'INDEX',
N'QC1',
N'QC2',
N'NTEMP',
N'SF135',
N'SFPREP',
N'NOS',
N'RR',
N'NTEMP2',
N'OHTA',
N'DUPS 36',
N'RSH',
N'DISC',
N'NARAT',
N'TRANS',
N'ABQ')
OR SS.SROOM_ID LIKE N'PGRS-%')
--WHERE SS.SROOM_ID IN (N'NOS', N'NARA')
-- OR SS.SROOM_ID LIKE 'SL%'
/*ORDER BY BOX_BOXNO */) AS source
(BoxID,BoxNum,BoxTitle,BoxLocation,BoxSourceCode,BoxSource,OST,FRC,WorkSite,dtLoaded,TribeInfo,dtFrom,dtTo, BoxStatus)
ON (target.BoxID = source.BoxID)
WHEN MATCHED AND (target.BoxNumber != source.BoxNum
OR target.BoxTitle != source.BoxTitle
OR target.BoxLocation != source.BoxLocation
OR target.BoxSourceCode != source.BoxSourceCode
OR target.BoxSource != source.BoxSource
OR target.OSTNumber != source.OST
OR target.FRCNumber != source.FRC
OR target.WorkSite != source.WorkSite
OR target.LoadedDate != source.dtLoaded
OR target.TribeInfo != source.TribeInfo
OR target.From_Date != source.dtFrom
OR target.To_Date != source.dtTo
OR target.BoxStatus != source.BoxStatus )
THEN UPDATE SET BoxNumber = source.BoxNum,
BoxTitle = source.BoxTitle,
BoxLocation = source.BoxLocation,
BoxSourceCode = source.BoxSourceCode,
BoxSource = source.BoxSource,
OSTNumber = source.OST,
FRCNumber = source.FRC,
WorkSite = source.WorkSite,
LoadedDate = source.dtLoaded,
TribeInfo = source.TribeInfo,
From_Date = source.dtFrom,
To_Date = source.dtTo,
BoxStatus = source.BoxStatus
WHEN NOT MATCHED THEN
INSERT (BoxID,BoxNumber,BoxTitle,BoxLocation,
BoxSourceCode,BoxSource,OSTNumber,FRCNumber,
WorkSite,LoadedDate,TribeInfo,From_Date,To_Date, BoxStatus)
VALUES (source.BoxID,source.BoxNum,source.BoxTitle,source.BoxLocation,
source.BoxSourceCode,source.BoxSource,source.OST,source.FRC,
source.WorkSite,source.dtLoaded,source.TribeInfo,source.dtFrom,source.dtTo, BoxStatus)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
--OUTPUT deleted.*, $action, inserted.*, GETDATE() INTO BISS_Historical..LogTblBoxInfo;
SELECT ##ROWCOUNT

Set all rows except 1

I have a flag in my database called published, I set this to 1 for a published row. My question is , is there a way to set all other rows to 0 and set a particular row to 1 with just one query.
At the moment im using:
$db->query("UPDATE my_table SET published = '0'");
$db->query("UPDATE my_table SET published = '1' WHERE id = '$id'");
UPDATE my_table SET published = IF (id = $id,1,0);
Use a CASE Statement
UPDATE my_table
SET published = CASE
WHEN id = '$id' THEN 1
ELSE 0 END
In MySQL, there's no boolean type (conditions return an integer), so this works too :
UPDATE my_table
SET published = (id = $id);
id = $id returns 0 if $id is different than id, else 1.

Possible to change these 2 SQL queries into 1?

Is it possible to change these 2 queries into 1?
Query #1:
UPDATE `pvdownloader`.`posts`
SET `exists` = 'y'
WHERE source = ANY (SELECT source FROM dbdownloader.posts)
AND `mangacount` = 0
AND NOT `exists` = 'm'
Query #2:
UPDATE `pvdownloader`.`posts`
SET `exists` = 'n'
WHERE `exists` = 'u'
AND `mangacount` = 0
I'm assuming it would be possible to make something like this with IF/ELSE but I can't figure out how to use it at all :<
Maybe something like this would work:
update
pvdownloader.posts
set
exists =
case
when source = any(select source from dbdownloader.posts) and mangacount = 0 and exists != 'm' then 'y'
when exists = 'u' and mangacount = 0 then 'n'
end
where
(source = any(select source from dbdownloader.posts) and mangacount = 0 and exists != 'm')
or
(exists = 'u' and mangacount = 0)
;
As #MostyMostacho suggested, I took the liberty of changing your logic to not have a double-negative.