I'm very much a newbie to programming.
I am trying to update my table column labelled 'bonus' with a new value of 505.99 if two conditions are met: if the givenname is Mary and their bonus is currently 155.99, or if their occupation is a Model and their bonus is also currently 155.99. 7 rows should be updated but only 1 is being updated.
The query looks like it should work to me so wondering what I am missing?
Looking for any pointers!
Thanks in advance
UPDATE customers
SET bonus = 505.99
WHERE occupation = 'Model' AND bonus = 155.99
OR givenname = 'Mary' AND bonus = 155.99;
Can you try to use parentheses like these?
UPDATE customers
SET bonus = 505.99
WHERE
(occupation = 'Model' AND bonus = 155.99)
OR
(givenname = 'Mary' AND bonus = 155.99);
You should use AND and OR conditions properly when you use those simultaneously.
Let us build your query :
As we know we are going to set value wherever following holds true.
Either occupation = 'Model' OR givenname = 'Mary'
This should be written with OR together
bonus = 155.99 : This we can add separately using AND in the select query.
So; the correct condition to use is (occupation = 'Model' OR givenname = 'Mary') and bonus = 155.99;
We can re-write the above query as :
UPDATE customers
SET bonus = 505.99
WHERE bonus = 155.99
AND (occupation = 'Model' OR givenname = 'Mary');
You can find more good examples here :
Related
I have two django-models
class ModelA(models.Model):
title = models.CharField(..., db_column='title')
text_a = models.CharField(..., db_column='text_a')
other_column = models.CharField(/*...*/ db_column='other_column_a')
class ModelB(models.Model):
title = models.CharField(..., db_column='title')
text_a = models.CharField(..., db_column='text_b')
other_column = None
Then I want to merge the two querysets of this models using union
ModelA.objects.all().union(ModelB.objects.all())
But in query I see
(SELECT
`model_a`.`title`,
`model_a`.`text_a`,
`model_a`.`other_column`
FROM `model_a`)
UNION
(SELECT
`model_b`.`title`,
`model_b`.`text_b`
FROM `model_b`)
Of course I got the exception The used SELECT statements have a different number of columns.
How to create the aliases and fake columns to use union-query?
You can annotate your last column to make up for column number mismatch.
a = ModelA.objects.values_list('text_a', 'title', 'other_column')
b = ModelB.objects.values_list('text_a', 'title')
.annotate(other_column=Value("Placeholder", CharField()))
# for a list of tuples
a.union(b)
# or if you want list of dict
# (this has to be the values of the base query, in this case a)
a.union(b).values('text_a', 'title', 'other_column')
In SQL query, we can use NULL to define the remaining columns/aliases
(SELECT
`model_a`.`title`,
`model_a`.`text_a`,
`model_a`.`other_column`
FROM `model_a`)
UNION
(SELECT
`model_b`.`title`,
`model_b`.`text_b`,
NULL
FROM `model_b`)
In Django, union operations needs to have same columns, so with values_list you can use those specific columns only like this:
qsa = ModelA.objects.all().values('text_a', 'title')
qsb = ModelB.objects.all().values('text_a', 'title')
qsa.union(qsb)
But there is no way(that I know of) to mimic NULL in union in Django. So there are two ways you can proceed here.
First One, add an extra field in your Model with name other_column. You can put the values empty like this:
other_column = models.CharField(max_length=255, null=True, default=None)
and use the Django queryset union operations as described in here.
Last One, the approach is bit pythonic. Try like this:
a = ModelA.objects.values_list('text_a', 'title', 'other_column')
b = ModelB.objects.values_list('text_a', 'title')
union_list = list()
for i in range(0, len(a)):
if b[i] not in a[i]:
union_list.append(b[i])
union_list.append(a[i])
Hope it helps!!
I have the following problem - I am coding an e-commerce website, that has promotions for a certain period of time. When time elapses promotion changes its corresponding database active value to 0. When I check for promotions the first condition is that active=1, but at some cases MySQL is ignoring it.
Here is an example of my most recent problem:
$productPromotion = $db->getResults('*', TABLE_PROMO, "active = '1'
AND (discount_subject = 'all_orders'
OR discount_subject_product = ".$values['product']['id'].")
OR (discount_subject = 'category'
AND discount_subject_category = ".$categoryId[0] . ") ORDER BY id ASC");
$db->getResult is a custom function that takes 3 parameters - What, Table and Where.
The problem is that it is returning promotions that are already expired and have active=0. Where is the problem with my sql?
You have to add brackets arround or
$productPromotion = $db->getResults('*', TABLE_PROMO, "active = '1'
AND
((discount_subject = 'all_orders' OR discount_subject_product = ".$values['product']['id'].")
OR (discount_subject = 'category' AND discount_subject_category = ".$categoryId[0] . ")) ORDER BY id ASC");
Also learn about prepared Statements to prevent SQL-injection
I want to write this SQL statement in cakePHP syntax:
UPDATE students SET status = 'graduated' WHERE age = '23' AND major = 'math';
Now, the way I am trying to do this in cake is
$student->updateAll( array('Student.status' => "'".$rowdata."'"),
array('Student.age' => $current_highest_age,'Student.major' =>
"'".$major."'"));
My variables: $rowdata = 'graduated'; $current_highest_age = 23; and $major = 'math'.
The table is not being updated. Is there a problem with my syntax? I will appreciate your help.
UPDATE ON THE QUESTION:
Actually, I found out where I was wrong in my syntax. The cake code should be 'Student.major' => $major instead of 'Student.major'=>"'".$major."'"
You are double escaping
updateAll expects the fields to be SQL expressions (or simply quoted strings) but the conditions should not be. As such, the query you're going to be generating right now is:
UPDATE
students
SET
status = 'graduated'
WHERE
age = '23' AND
major = '\'math\''
To prevent the extra quotes, which will cause the syntactically-valid statement to match 0 rows, just let Cake take care of your conditions for you as with other methods:
$student->updateAll(
array('Student.status' => "'".$rowdata."'"),
array(
'Student.age' => $current_highest_age,
'Student.major' => $major
)
);
Easy way to update a field of a Model
$this->Testing->updateAll(
array('Testing.door_open_close' => $door_open_close), // value that is updated
array('Testing.id' => $zoneId) // condition field of a Model
);
UPDATE students ...
^^^^^^^^--- student WITH an S
v.s.
array('Student.age')
^^^^^^^ - student WITHOUT an S
I need to check if the column exam has a value of true. So I set this up but it doesn't work...
#exam_shipments = Shipment.where("exam <> NULL AND exam <> 0 AND customer_id = ?", current_admin_user.customer_id)
# This one gives me error "SQLite3::SQLException: no such column: true:"
#exam_shipments = Shipment.where("exam = true AND customer_id = ?", current_admin_user.customer_id)
#exam_shipments = Shipment.where("exam = 1 AND customer_id = ?", current_admin_user.customer_id)
You should really just stick to AR syntax:
#exam_shipments = Shipment.where(:exam => true, :customer_id => current_admin_user.customer_id)
Assuming :exam is a boolean field on your Shipment model. ActiveRecord takes care of converting your query to the proper syntax for the given database. So the less inline SQL you write, the more database-agnostic and portable your code will be.
Why do you need do execute SQL?
It's much easier just to do
#exam_shipments = Shipment.find_by_id(current_admin_user.customer_id).exam?
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