MYSQL statement together OR and AND - mysql

I have a table in MySQL named sale with 3 columns like below :
sale:
id|customers|type
I want to select sales that has type!=2 OR
sales that has type=2 and customers!=0
I write statement like this :
sale.type != 2 OR (sale.type = 2 AND sale.customers != 0 )
but it doesn`t give me correct rows .
Also I have to use AND for other columns in this query but the operators between all of them is AND , just here I use OR .

Just remember thus rule: bracket the OR!
where foo = 'bar'
and (sale.type != 2 OR (sale.type = 2 AND sale.customers != 0 ) )
and blah = 3
Actually your condition can be simplified to:
( sale.type != 2 OR sale.customers != 0 )
Because logically checking for sale.type = 2 is redundant.

do you want sales.type not equal to 2 or (sales.type equal to 2 when you have customers not equal to 0?)
you can use HAVING and WHERE together.
Select * from sales where type !=2 or (type=2 HAVING customers !=0);

Just I try with this i found working: sqlfiddle
select * from sale where
sale.type != 2 OR (sale.type = 2 AND sale.customers != 0 )

Related

sql rank row results

I"m trying to add a new col that shows the rank (or sequence) of row results by date.
I've written:
SELECT
#row_number:=(CASE
WHEN #member_id = lh.member_id and lc.ladder_advocacy is not null
THEN #row_number + 1
when #member_id = lh.member_id and lc.ladder_advocacy is null then "null"
ELSE 1 /* there is an error here - i need it to return a 1 if not null, then 2 for the 2nd instance, etc */
END) AS rank_advocacy,
#member_id:=lh.member_id AS member_id,
lh.ladder_change,
lc.name,
lc.ladder_advocacy,
lc.ladder_elected,
lc.ladder_policy,
lc.ladder_engagement,
lc.ladder_newventure,
lc.ladder_collective,
lc.is_trigger
FROM
leenk_ladder_history AS lh
LEFT JOIN
leeds_so.leenk_ladder_config AS lc ON lh.ladder_config_id = lc.id
WHERE
ladder_change = 1 AND trigger_active = 1
ORDER BY member_id, trigger_event_date DESC;
There is an error at row 4, and I'm not sure how to fix it. For the first result, I want to return 1. for the second results, I want to return #row_number + 1. Third result, #row_number+2 (etc).
How do I achieve this?
I don't understand how the condition lc.ladder_advocacy is not null is being used. However, the basic structure is:
SELECT (#row_number = IF(#member_id = lh.member_id, #row_number + 1
IF(#member_id := lh.member_id, 1, 1)
)
) as rank_advocacy,
lh.ladder_change,
. . .
Some really important points:
You need to assign #member_id and #row_number in the same expression. MySQL (as with all other databases) does not guarantee the order of evaluation of expressions.
In more recent versions of MySQL, I think the ORDER BY needs to go in a subquery, with the variable expressions in the outer query.

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)

Not an Intersect (IN) but sort of. Where Col a row x intersects with col b.Mysql

I have a matrix table. 6 columns wide and 6 rows deep.The first column has the numbers 0, 5,4,3,2,1 in that order. The first row in the table is 0,1,2,3,4,5
so like this:
Column names RM0 RM1 RM2 RM3 RM4 RM5
0 1 2 3 4 5
5
4
3
2
1
each of the rows has words in it ie, MEDIUM, HIGH, CRITICAL etc.
I have a form the user fills out that requires them to give a rating from 1-5 in two categories. Their selections correspond to one of the words in the matrix. SO..after all that...I need to be able to select from the table something like this:
SELECT FROM TBLX WHERE RM0=4 INTERSECTS WITH RM4
I have look at IN but everything I see so far still requires you to have another WHERE x=y part. Could I dump the whole table into an array somehow get what Im after? As you can see, Im clueless in this regard.
You can do something like this:
SELECT CASE :b2
WHEN 1 THEN t.rm1
WHEN 2 THEN t.rm2
WHEN 3 THEN t.rm3
WHEN 4 THEN t.rm4
WHEN 5 THEN t.rm5
ELSE ''
END AS `the_word`
FROM TBLX t
WHERE t.rm0 = :b1
I'm confused by the table design. And even more confused by the first row... if you want to get that incorporated in the query, that would be inordinately complex.
In terms of a normal relational design, we'd represent this as rows for each pair of values, with a single word on each row.
mymatrix
x_rating y_rating the_word
-------- -------- --------
1 1 LOW
1 2 LOW
1 3 MEDIUM
1 4 MEDIUM
1 5 MEDIUM
2 1 LOW
2 2 MEDIUM
2 3 MEDIUM
...
5 5 HIGH
An example of a query to get "the word" would be something like this:
SELECT mx.the_word
FROM mymatrix mx
WHERE mx.x_rating = :b1
AND mx.y_rating = :b2
To use that same query pattern with the original table, we could get that original table converted to look like the mymatrix table, using the values from the RM1 through RM5 columns in the RM0=0 row as the y_rating value. The SQL to do that is rather cumbersome:
SELECT mx.the_word
FROM (
SELECT t1.rm0 AS x_rating
, s1.rm1 AS y_rating
, t1.rm1 AS the_word
FROM mytable t1
JOIN mytable s1
ON s1.rm0 = 0
AND t1.rm0 > 0
UNION ALL
SELECT t2.rm0 AS x_rating
, s2.rm1 AS y_rating
, t2.rm1 AS the_word
FROM mytable t2
JOIN mytable s2
ON s2.rm0 = 0
AND t2.rm0 > 0
UNION ALL
SELECT t3.rm0 AS x_rating
, s3.rm1 AS y_rating
, t3.rm1 AS the_word
FROM mytable t3
JOIN mytable s3
ON s3.rm0 = 0
AND t3.rm0 > 0
UNION ALL
SELECT t4.rm0 AS x_rating
, s4.rm1 AS y_rating
, t4.rm1 AS the_word
FROM mytable t4
JOIN mytable s4
ON s4.rm0 = 0
AND t4.rm0 > 0
UNION ALL
SELECT t5.rm0 AS x_rating
, s5.rm1 AS y_rating
, t5.rm1 AS the_word
FROM mytable t5
JOIN mytable s5
ON s5.rm0 = 0
AND t5.rm0 > 0
) mx
WHERE mx.x_rating = :b1
AND mx.y_rating = :b2
I ended up taking a different route. I still used the matrix table but instead of trying to access when I need to retrieve information I queried the table once, took all the information and put it into an array like this:
sql = "SELECT * FROM `tblriskmatrix`";
if (!$conn->query($sql)) {
echo "query failed: (" . $conn->errno . ") " . $conn->error;
}
$result = $conn->query($sql);
$arrayOfMatrix = array();
while ($row = $result->fetch_assoc()) {
$arrayOfMatrix[] = $row;
}
I then put the array into a session variable like this:
$_SESSION['arrayOfMatrix'] = $arrayOfMatrix;
I then created some functions to get the keys pressed and passed them to another function that did an ajax call, passing the variables of the key presses script that took those variables and passed them into my session variable and returned the desired result. Like this:
session_start();
$a = $_GET['var_a'];
$b = $_GET['var_b'];
$response = array('response' => $_SESSION['arrayOfMatrix'][$a]["RM$b"]);
echo json_encode($response);
The response is then passed to a form element and displayed. So with the matrix table in the session variable as an array I can easily extract the contents of what is in cell of row x within column y. Not sure if its the most technically correct route but it works.

Create one alias virtual colum containing value of either of two columns

See the SQL query below:
SELECT *
FROM
(SELECT
h.hotel_id AS id,h.hotel_city AS city,h.hotel_name AS hotelname,
h.hotel_star AS hotelcat, hwd.double_spl_rate, hwd.third_party_rate,
hwd.extra_bed_spl_rate, hwd.meal_plan_spl,
hwd.third_party_extra_bed, hwd.third_party_meal_plan,
hwd.room_category, hrd.hotel_rate_from, hrd.hotel_rate_to
FROM
hotels_list AS h
INNER JOIN
hotel_rate_detail AS hrd ON h.hotel_id = hrd.hotels_id
INNER JOIN
hotel_week_days AS hwd ON hrd.hotel_id = hwd.h_id
WHERE
(('2015-07-31' BETWEEN hrd.hotel_rate_from AND hrd.hotel_rate_to)
OR
('2015-08-01' BETWEEN hrd.hotel_rate_from AND hrd.hotel_rate_to)
)
AND (h.hotel_city = '1')
AND (hwd.double_spl_rate != 0 OR hwd.third_party_rate != 0)
AND (h.hotel_star = '4')
ORDER BY
hwd.double_spl_rate, hwd.third_party_rate ASC) AS result_table
GROUP BY
result_table.id
ORDER BY
result_table.double_spl_rate, result_table.third_party_rate ASC
LIMIT 0,5;
OUTPUT is attached below:
In the above output there are two columns double_spl_rate and third_party_rate which can be either 0 or a value greater than zero.
How can I create a virtual column alias which only contain values greater the zero. Let us suppose the column is final_rate which will contain values as
id | final_rate
533 | 3776
9228 | 3000
Yes, you can do this like so:
select
id,
case
when coalesce(double_spl_rate,0) = 0
then third_party_rate
else double_spl_rate
end as final_rate
from table
The coalesce operator will set double_spl_rate to 0 if it's null, and the case expression will return third_party_rate if double_spl_rate is 0.
If double_spl_rate cannot be null you can skip the coalesce part.
Note that the code above will always prefer the value in double_spl_rate and disregard the other value if both values are greater than 0. If you don't want this you could extend the logic in the case expression to account for that and return the sum of the values instead. Or you could simply just return third_party_rate + double_spl_rate in all cases.

Update column depending on other column by calculation

seems like a stupid question...
I have a mysql table where I want to modify column A to a number 0 or 1 depending on the condition of another column B
So: if( B > 500 ) A = 1 ELSE A = 0
Column A = INT
Column B = DOUBLE
How do you do something like this in sql?
Thanks,
Erik
Try the following statement,
UPDATE tableName
SET A = (B > 500)
SQLFiddle Demo
(B > 500) is a boolean arithmetic in mysql which returns 1 and 0 for true and false , respectively.
You can also use CASE for much more RDBMS friendly,
UPDATE tableName
SET A = CASE WHEN B > 500 THEN 1 ELSE 0 END