MySQL UPDATE only if field in other table meets condition - mysql

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;

Related

HOW do i do a data append against multiple columns

I added a column into table A and right now it is empty. What i want to do is take the phone column from table consumer and input it into appphone of table diabetic as long as the first name, last name, address, city, state, and zip, match up in both tables. Below is the query i have been trying and in theory should work but is not. I keep getting the same error no matter which way i change the query.--
error 'subquery returns more than one row'
UPDATE Diabetic_DB
SET Diabetic_DB.AppPhone = (SELECT Consumer.PHONE FROM Consumer
WHERE Consumer.FN = Diabetic_DB.FirstName
and Consumer.LN = Diabetic_DB.LastName and Consumer.ADDR = Diabetic_DB.Address1
and Consumer.CITY = Diabetic_DB.City and Consumer.ST = Diabetic_DB.State
and Consumer.ZIP = Diabetic_DB.Zip)
WHERE EXISTS (SELECT DISTINCT(PHONE) FROM Consumer WHERE Consumer.FN = Diabetic_DB.FirstName
and Consumer.LN = Diabetic_DB.LastName and Consumer.ADDR = Diabetic_DB.Address1
and Consumer.CITY = Diabetic_DB.City and Consumer.ST = Diabetic_DB.State
and Consumer.ZIP = Diabetic_DB.Zip)
the original query i ran looked like this.
UPDATE Diabetic_DB
SET Diabetic_DB.AppPhone = Consumer.PHONE
WHERE EXISTS (SELECT * FROM Consumer WHERE Consumer.FN = Diabetic_DB.FirstName
and Consumer.LN = Diabetic_DB.LastName and Consumer.ADDR = Diabetic_DB.Address1
and Consumer.CITY = Diabetic_DB.City and Consumer.ST = Diabetic_DB.State
and Consumer.ZIP = Diabetic_DB.Zip)
Try something like this:
UPDATE Diabetic_DB
INNER JOIN Consumer ON
Consumer.FN = Diabetic_DB.FirstName
and Consumer.LN = Diabetic_DB.LastName and Consumer.ADDR = Diabetic_DB.Address1
and Consumer.CITY = Diabetic_DB.City and Consumer.ST = Diabetic_DB.State
and Consumer.ZIP = Diabetic_DB.Zip
SET Diabetic_DB.AppPhone = Consumer.PHONE

CakePHP Using "Group By" in Virtual Field Not Working

I have the following virtual field on my Page model
function __construct($id = false, $table = null, $ds = null) {
$this->virtualFields['fans'] = 'SELECT COUNT(Favorite.id) FROM favorites AS Favorite WHERE Favorite.page_id = Page.id AND Favorite.status = 0';
parent::__construct($id, $table, $ds);
}
This works as expected and displays the number of users who have added the page to their favorites. The issue is that, during development, some rows have duplicate user_id to page_id pairs so it returns the incorrect number or unique users. I tried adding a group by clause like so
$this->virtualFields['fans'] = 'SELECT COUNT(Favorite.id) FROM favorites AS Favorite WHERE Favorite.page_id = Page.id AND Favorite.status = 0 GROUP BY Favorite.user_id';
But it does not work. I tried debugging the issue but I receive the error message "allowed memory size exhausted". I also tried using SELECT COUNT('Favorite.user_id') and SELECT DISTINCT('Favorite.user_id') neither of which worked either. I believe DISTINCT is further away from the answer as that would return an array (I believe?)
Is this a known CakePHP issue? Am I implementing the group by wrong? Is there another solution to do this other than afterfind?
try this
SELECT COUNT(DISTINCT Favorite.user_id)
like that :
$this->virtualFields['fans'] = 'SELECT COUNT(DISTINCT id) FROM favorites WHERE status = 0';

Declare multiple variables for single variable in mysql

My query pulls list of bug items by jira issue (goes specific to component of jira), I need to find out how can i enter multiple pkey in this query, single pkey works fine, however when I declare multiple pkey it throws an error message.
In following query, abc-123 is a jira bug id, subquery finds component name and 2nd subquery will fetch project name, remaining query will pull list of bugs associated with the component, I would like to enter 'def-456', 'jdk-985' next to 'abc-123' , I tried setting new variable however it did not work, can someone please help
$
set #pkey := 'abc-123';
select jiraissue.*, co.*
from jiraissue,project,issuetype,nodeassociation,component,
customfieldvalue cv
,customfieldoption co
where
component.cname = (SELECT component.cname
FROM nodeassociation, component, jiraissue
WHERE component.ID = nodeassociation.SINK_NODE_ID
AND jiraissue.id = nodeassociation.SOURCE_NODE_ID
AND nodeassociation.ASSOCIATION_TYPE = 'IssueComponent'
AND pkey = #pkey) and
project.pkey = (SELECT substring_index(jiraissue.pkey,'-',1) as project_name
FROM nodeassociation, component, jiraissue
WHERE component.ID = nodeassociation.SINK_NODE_ID
AND jiraissue.id = nodeassociation.SOURCE_NODE_ID
AND nodeassociation.ASSOCIATION_TYPE = 'IssueComponent'
AND pkey = #pkey) and
issuetype.pname = 'Bug' and
jiraissue.project = project.id and
jiraissue.issuetype = issuetype.id and
nodeassociation.association_type = 'IssueComponent' and
nodeassociation.source_node_entity = 'Issue' and
nodeassociation.source_node_id = jiraissue.id and
nodeassociation.sink_node_entity = 'Component' and
nodeassociation.sink_node_id = component.id
and jiraissue.id = cv.issue
and cv.stringvalue = co.id
and cv.customfield = 10020;
Try replacing
AND pkey = #pkey
with this:
AND pkey in (#pkey, #pkey1, #pkey2)
and then at the top:
set #pkey := 'abc-123', #pkey1 := 'def-456', #pkey2 = 'ghi-789'

Complex MySQL query issue

I have a somewhat complex mySQL query I am trying to execute. I have two parameters: facility and isEnabled. Facility can have a value of "ALL" or be specific ID. isEnabled can have value of "ALL" or be 0/1.
My issue is that I need to come up with logic that can handle the following scenarios:
1) Facility = ALL AND isEnabled = ALL
2) Facility = ALL AND isEnabled = value
3) Facility = someID AND isEnabled = ALL
4) Facility = someID AND isEnabled = value
The problem is that I have several nested IF statements:
IF (Facility = 'ALL') THEN
IF (isEnabled = 'ALL') THEN
SELECT * FROM myTable
ELSE
SELECT * FROM myTable
WHERE isEnabled = value
END IF;
ELSE
IF (isEnabled = 'ALL') THEN
SELECT * FROM myTable
WHERE facility = someID
ELSE
SELECT * FROM myTable
WHERE facility = someID AND isEnabled = value
END IF;
END IF;
I would like to be able to combine the logic in the WHERE clause using either a CASE statement or Conditional's (AND/OR) but I am having trouble wrapping my head around it this morning. Currently the query is not performing as it is expected to be.
Any insight would be helpful!
Thanks
You could do this...
SELECT
*
FROM
myTable
WHERE
1=1
AND (facility = someID OR Facility = 'ALL')
AND (isEnabled = value OR isEnabled = 'ALL')
However, this yields a poor execution plan - it's trying to find one size fits all, but each combination of parameters can have different plans depending on data, indexes, etc.
This means that it is better to build the query dynamically
SELECT
*
FROM
myTable
WHERE
1=1
AND facility = someID -- Only include this line if : Facility = 'ALL'
AND isEnabled = value -- Only include this line if : isEnabled = 'ALL'
I know it can feel dirty to use dynamic queries, but this is a good corner case as to when then really can excel. I'll go find a spectacularly informative link for you now. (It's a lot to read, but it's very worth learning from)
Link : Dynamic Search

How do I update a table with fields selected from another table?

Although there are many questions similar to this, such as
"Updating a record from another table", but i could not get this working.
I have a query that selects and updates table sem_stdexamfinresmark. The select subquery returns multiple rows of data whose size may not be equal to the table being updated, but the update is now working.
The query looks like :
update sem_stdexamfinresmark sr,
(select
se.currsession,
str.studentid,
str.classid,
str.subjectid,
str.aggScore*(select gbtp.percentage from gb_termpercentage gbtp where gbtp.termname = se.examtype)/100 as aggPer,
str.aggGrade
from
sem_stdexamtermresr str,
sem_exam se
where
str.examid=se.examid and
se.examtype = 'Second Term' and
se.currsession =1 and classid='8'
) s
set
sr.SecondTermMark = s.aggPer and
sr.SecondTermGrade = s.aggGrade
where
sr.studentid=s.studentid and
sr.subjectid=s.subjectid and
s.currsession = s.currsession and
sr.classid='8';
EDIT:
update sem_stdexamfinresmark
set
sr.SecondTermMark = s.aggPer and
sr.SecondTermGrade = s.aggGrade
from
(select
se.currsession,
str.studentid,
str.classid,
str.subjectid,
str.aggScore*(select gbtp.percentage from gb_termpercentage gbtp where gbtp.termname = se.examtype)/100 as aggPer,
str.aggGrade
from
sem_stdexamtermresr str,
sem_exam se
where
str.examid=se.examid and
se.examtype = 'Second Term' and
se.currsession = 1 and classid='8'
) s
where
sr.studentid=s.studentid and
sr.subjectid=s.subjectid and
s.currsession =1 and
sr.classid='8';
select * from sem_exam;
update sem_exam set currsession =1;
try something that looks more like:
update foo
set col = bar.col
from bar
where ...
This is what happens when one loses sleep :( I just did a silly mistake here and added "and"