How can I combine ANDs and ORs in my SQL statement - mysql

I have this SQL statement:
SELECT * FROM `table` WHERE type = 3 OR type = 5 OR type = 4 and table.deleted = 1;
I've read that I can use parenthesis to accomplish this but I was wondering if then this would be valid:
SELECT * FROM `table` WHERE (type = 3 OR type = 5 OR type = 4) and table.deleted = 1;
OR
SELECT * FROM `table` WHERE (type = 3 OR type = 5) OR type = 4 and table.deleted = 1;

Both of these would be valid, but since AND has higher precedence than OR, they would mean different things:
Your first parenthesized query would pick deleted rows with types 3, 4, 5
Your second parenthesized query would select all rows with types 3, 5, in addition to deleted rows of type 4; this is the same meaning as in the original query without parentheses.
You can avoid the confusion altogether by using operator IN, like this:
SELECT * FROM `table` WHERE type IN (3, 4, 5) AND table.deleted = 1;
or if you wanted the second meaning
SELECT * FROM `table` WHERE type IN (3, 5) OR (type = 4 AND table.deleted = 1)

What you need is IN operator like
SELECT * FROM `table`
WHERE type IN ( 3, 5, 4) and deleted = 1;

AND has higher precedence than OR, so your first and third filters are equivalent to:
type = 3 OR type = 5 OR (type = 4 and table.deleted = 1)
Your second filter could equivalently be expressed using IN():
type IN (3, 5, 4) and table.deleted = 1

Related

Is there a way to make an AND operation over a column of TINYINT(1) in MYSQL?

I got the following table and I need to return 1 if all rows have disponibilidad = 1
The following QUERY works just fine, but i was looking for a more efficient way of doing it.
QUERY:
SELECT IF(AVG(disponibilidad) < 1, 0, 1) AS newResult
FROM pasteleria.compone
RIGHT JOIN pasteleria.ingredientes
ON pasteleria.compone.id_ingrediente = pasteleria.ingredientes.id_ingrediente
WHERE id_componente = 1;
RESULT:
As I see it, with an 'AND' it would be far more efficient, since it wouldn't have to do AVG().
MySql does not support a boolean AND aggregate function like Postgresql's bool_and.
Why not a simple MIN():
SELECT MIN(disponibilidad) AS newResult
FROM pasteleria.compone
RIGHT JOIN pasteleria.ingredientes
ON pasteleria.compone.id_ingrediente = pasteleria.ingredientes.id_ingrediente
WHERE id_componente = 1;
This will return 1 only if all values of the column are 1 (provided the column is not nullable) and 0 if there is at least one row with 0.
How about something like
SELECT IF(COUNT(*)>0,0,1) AS newResult
FROM pasteleria.compone
RIGHT JOIN pasteleria.ingredientes
ON pasteleria.compone.id_ingrediente = pasteleria.ingredientes.id_ingrediente
WHERE id_componente = 1
AND disponibilidad <> 1
so that if there are any rows where disponibilidad is not 1, you output 0, otherwise if it's zero (so all disponibilidad values are 1) you output 1?

Why does mySQL query give unexpected results?

This is my mySQL query :
SELECT mCat,postSta
FROM `info_posts`
WHERE `mCat` = 'Mobiles' AND `sCat` = 'Mobile Phones' AND `brCat` = 'Apple' AND `postSta` = 1 OR `postSta` = 4 OR `postSta` = 5
The problem with this is that it selects all the criteria properly however it also fetches the things where postSta = 4 and 5 take a look at the screenshot. I want to select things which match the criteria of mCat,sCat and brCat where postSta is 1 or 4 or 5.
Use IN:
SELECT mCat,postSta
FROM info_posts
WHERE mCat = 'Mobiles' AND sCat = 'Mobile Phones' AND brCat = 'Apple' AND
postSta IN (1, 4, 5)
The problem is that you need parentheses in your query, but IN is a better approach.
The logical "and" operation has a higher precedence than the logical "or" operator. The logic you're looking for can be achieved by surrounding the series of "or" conditions with parenthesis:
SELECT `mCat`, `postSta`
FROM `info_posts`
WHERE `mCat` = 'Mobiles' AND
`sCat` = 'Mobile Phones' AND
`brCat` = 'Apple' AND
(`postSta` = 1 OR `postSta` = 4 OR `postSta` = 5)

Mysql query returns wrong data with where clause

I am using the following query to get data from mysql database and I get wrong data. I want to get all data with the cart_Status of 2 or 3 which have the view_Status of 1:
SELECT * FROM `cart` WHERE `view_Status` = 1 AND cart_Status = 2 OR `cart_Status` = 3
This is how my data structure and table looks like:
But in result, it returns something regardless of view_Status = 1 which is not my target.
it returns :
Of course, it should not return anything! But, it does!
This is about operator precendence.
Your query evaluates as
SELECT * FROM `cart` WHERE (`view_Status` = 1 AND cart_Status = 2) OR `cart_Status` = 3
You should to add parentheses:
SELECT * FROM `cart` WHERE `view_Status` = 1 AND (cart_Status = 2 OR `cart_Status` = 3)
SELECT * FROM `cart` WHERE `view_Status` = 1 AND (cart_Status = 2 OR `cart_Status` = 3)
or better
SELECT * FROM `cart` WHERE `view_Status` = 1 AND cart_Status in (2, 3);
You appear to be learning SQL. Use parentheses in the WHERE clause, particularly when you mix AND and OR.
However, in your case, IN is a better solution:
SELECT c.*
FROM `cart` c
WHERE c.view_Status = 1 AND cart_Status IN (2, 3);
It's a problem with operators precedence. Typically AND is executed before OR in programming languages (think of AND as of multiplication of bits, and of OR as of addition of bits and precedence becomes familiar). So, your condition:
`view_Status` = 1 AND cart_Status = 2 OR `cart_Status` = 3
is parsed like this:
(`view_Status` = 1 AND cart_Status = 2) OR `cart_Status` = 3
which results in all rows with specific cart_Status to be selected. You have to add parenthesis around the second clause:
`view_Status` = 1 AND (cart_Status = 2 OR `cart_Status` = 3)
or, even shorter:
`view_Status` = 1 AND cart_Status IN (2, 3)

how to select from mysql table from matlab variable (array/cell)

I have a table like this
The table in mysql
and I have a variable x in matlab
x=[1 5 6 8 10 21 99];
now I want to select like this
select * from tablename where key1 = x
I know mysql query must be string, and my variable x in matlab may be too long.
So how to do this in matlab? I failed in searching. Thanks
conn = database('instancename','username','password');
I know I can do this like
sql = 'select * from tablename where key in (1,5,6,8,10,21,99)'
The question is my x isn't constant and sometime could be a 1*N cell ( whose element is char), I want to put it into a script.
In SQL Server you write your query like this:
select * from tablename where key1 in {1, 5, 6, 8, 10, 21, 99}
I don't know about MY SQL but I imagine it is very similar. Which means all you need to do is convert x to the string '1, 5, 6, 8, 10, 21, 99' which you could do like this:
x_str = strjoin(cellstr(num2str(x'))',',')
and now the whole query becomes
query = sprintf('SELECT * FROM tablename WHERE key1 IN {%s}', x_str);
As an aside, another way to create x_str could be:
x_str = sprinft('%d, ', x);
x_str(end) = [];

MySql Insert Dynamic Query with Nested Select

I'm trying a MySQL Insert Query with mix of static & Dynamic Values. The INSERT command is.
INSERT INTO ebdb.requestaction(RequestID,
ActionID,
TransactionID,
IsActive,
IsComplete)
VALUES (
1,
**Dynamic Value from Below Query,
Dynamic Value from Below Query,**
1,
0);
The Query to fetch the field 2 & 3 come from the below Query.
SELECT transitionaction.TransitionID, transitionaction.ActionID
FROM transitionaction
INNER JOIN transition
ON transitionaction.TransitionID = transition.TransitionID
WHERE transition.TenantID = 1
AND transition.ProcessID = 1
AND transition.CurrentStateID = 1
ORDER BY transitionaction.TransitionID;
I'm doing something wrong in here.
Please guide me as to how this can be achieved in the most optimized way.
You can select static values as part of a query, e.g.:
INSERT INTO ebdb.requestaction(RequestID, ActionID, TransactionID, IsActive, IsComplete)
SELECT 1, transitionaction.ActionID, transitionaction.TransitionID, 1, 0
FROM transitionaction
INNER JOIN transition
ON transitionaction.TransitionID = transition.TransitionID
WHERE transition.TenantID = 1
AND transition.ProcessID = 1
AND transition.CurrentStateID = 1
ORDER BY transitionaction.TransitionID;
For more information, refer to MySQL's Insert...Select Syntax