Where clause not working in my mysql query - mysql

I have implemented a Mysql query with many where conditions but it is not giving right result.I have to find data where user_id is not equal to 7 but it is giving me result with user_id 7.here is both queries i run but not giving me right result.
SELECT *
FROM `tr_truck`
WHERE (`user_id` != 7 AND `body_type_id` = 1 )
AND ( `truck_capacity_id` = 1 AND `truck_wheel_id` = 2 )
OR ( `truck_wheel_id` = 2 AND `truck_length_id` = 1 )
OR (`truck_capacity_id` = 1 AND `truck_length_id` = 1 )
and another query i run is
SELECT *
FROM `tr_truck`
WHERE ( `truck_capacity_id` = 1 AND `truck_wheel_id` = 2 )
OR ( `truck_wheel_id` = 2 AND `truck_length_id` = 1 )
OR (`truck_capacity_id` = 1 AND `truck_length_id` = 1 )
AND `user_id` NOT IN (7) AND `body_type_id` = 1
I also tried to replave <> operator with != but to no avail.Here is screenshot of my database result.
https://prnt.sc/kskl08

Can you please try this, I rearrange the brackets arragement
query 1
SELECT *
FROM `tr_truck`
WHERE (`user_id` != 7 AND `body_type_id` = 1 AND `truck_capacity_id` = 1 AND `truck_wheel_id` = 2 )
AND
( (`truck_wheel_id` = 2 AND `truck_length_id` = 1 )
OR ( `truck_capacity_id` = 1 AND `truck_length_id` = 1 ))
query 2
SELECT *
FROM `tr_truck`
WHERE (( `truck_capacity_id` = 1 AND `truck_wheel_id` = 2 )
OR ( `truck_wheel_id` = 2 AND `truck_length_id` = 1 )
OR (`truck_capacity_id` = 1 AND `truck_length_id` = 1 ) )
AND (`user_id` NOT IN (7) AND `body_type_id` = 1 )

Related

2 where condition one SQL sentence

I want to fetch that SQL rows:
SELECT aa.*
FROM Answers AS aa
WHERE event_id = 1 AND
( (aa.form_item_id = 1 AND form_item_reply = "John") AND
(aa.form_item_id = 2 AND form_item_reply = "Doe")
)
ORDER BY aa.id DESC
But it's given wrong result, I want to fetch that (aa.form_item_id = 1 AND form_item_reply = "John") and (aa.form_item_id = 2 AND form_item_reply = "Doe").
It have to give me above 2 condition result.
You can use OR
SELECT aa.* FROM Answers AS aa WHERE event_id = 1 AND
(
(aa.form_item_id = 1 AND form_item_reply = "John")
OR (aa.form_item_id = 2 AND form_item_reply = "Doe")
) ORDER BY aa.id DESC
Perhaps you just want OR:
SELECT aa.*
FROM Answers AS aa
WHERE event_id = 1 AND
( (aa.form_item_id = 1 AND form_item_reply = 'John') OR
(aa.form_item_id = 2 AND form_item_reply = 'Doe')
)
ORDER BY aa.id DESC

mysql matching multiple and's and or's

I am trying to get rows from a table where there are matches on multiple other tables.
This is the query I am running.
SELECT qt.*, DATEDIFF(CURRENT_DATE, STR_TO_DATE(up.DOB, '%m-%d-%Y')) / 365 AS Age
FROM UserProfile AS up, Game AS g, QuestionTable AS qt
WHERE NOT EXISTS(SELECT * FROM Options WHERE UserID = 75 AND QID = qt.QID AND DateTime >= CURDATE())
AND g.Active = 1 AND g.QID = qt.QID
AND (((g.Gender = up.Gender OR g.Gender = 'B') AND ((g.City = up.City AND g.Zip = up.Zip AND g.Country = up.Country) OR g.Home = 0) AND ((Age BETWEEN g.Maximum AND g.Minimum) OR g.Age = 0) AND ((SQRT( POW( 69.1 * ( g.Latitude - -93.5746359 ) , 2 ) + POW( 69.1 * ( 44.9737707 - g.Longitude ) * COS( g.Latitude / 57.3 ) , 2 ) ) > g.Distance) OR g.Geo = 0)) OR g.Special = 0)
GROUP BY qt.QID
I have ran this expression through C# and it returns true, yet it is only matching on the 'g.Special = 0' part through MySql.
Any help on this would be much appreciated!
Resolved the issue by fixing some mistakes I made and changed the query to this,
SELECT *
FROM QuestionTable AS qt
WHERE NOT EXISTS
(SELECT * FROM Options WHERE UserID = 75 AND QID = qt.QID AND DateTime >= CURDATE())
AND EXISTS(SELECT g.* FROM UserProfile AS up, Game AS g WHERE g.Active = 1 AND g.QID = qt.QID AND(g.Special = 0 OR(
(g.Gender = up.Gender OR g.Gender = 'B') AND
((g.City = up.City AND g.zip = up.Zip AND g.Country = up.Country) OR g.Home = 0) AND
((SQRT( POW( 69.1 * ( g.Latitude - 44.9737707 ) , 2 ) + POW( 69.1 * ( -93.5746359 - g.Longitude ) * COS( g.Latitude / 57.3 ) , 2 ) ) < g.Distance) OR g.Geo = 0) AND
((DATEDIFF(CURRENT_DATE, STR_TO_DATE(DOB, '%m/%d/%Y'))/365.25 BETWEEN g.Minimum AND g.Maximum) OR g.Age = 0))))

Create INTERSECT query in MySQL

I have a tables
ppv (product_id | property_id | value_id)
and
v (id | property_id | value)
I try to make query to get products where:
select product_id from v, ppv as t INNER JOIN ppv as t2
ON t.product_id = t2.product_id and t1.property_id = t2.property_id
where
( t1.property_id = 1 and v.value > $a and v.value < $b )
and
( t2.property_id = 2 and v.value > $c and v.value < $d )
But havn`t any results. Please help.
So,
ppv (product_id | property_id | value_id)
1 1 50
1 2 2
1 3 3
2 1 28
2 2 2
2 3 29
Next table
v( id | property_id | value)
2 2 3
3 3 2
28 1 2600000
29 3 3
50 1 2500000
** I found a solution to this problem in this way **
SELECT `product_id`,
CONVERT(GROUP_CONCAT(v.`property_id`) USING cp1251) as properties
FROM `values` as v INNER JOIN `product_property_values` as ppv
ON ppv.value_id = v.id
WHERE
(v.`property_id` = 1 and v.value >= 2500000 and v.value <= 3000000 )
or
(v.`property_id` = 2 and v.value >= 1 and v.value <= 3 )
GROUP by product_id
HAVING LOCATE('1', properties) and LOCATE('2', properties)
Th result:
test 1
v.`property_id` = 1 and v.value >= 2500000 and v.value < 3000000
v.`property_id` = 2 and v.value >= 1 and v.value <= 2
product_id properties
Empty
test2
v.`property_id` = 1 and v.value >= 2550000 and v.value < 3000000
v.`property_id` = 2 and v.value >= 1 and v.value <= 4
product_id properties
2 2,1
test3
v.`property_id` = 1 and v.value >= 2000000 and v.value < 3000000
v.`property_id` = 2 and v.value >= 1 and v.value <= 4
product_id properties
1 1,2
2 2,1
It's OK!
It doesn't look like you are actually joining table v. Also, I don't believe it is necessary to link to ppv twice. Try:
SELECT ppv.product_id
FROM v
INNER JOIN ppv ON v.property_id = ppv.property_id
WHERE
(ppv.property_id = 1 and v.value > $a and v.value < $b )
OR
(ppv.property_id = 2 and v.value > $c and v.value < $d )
First problem: what is t1 ?
Second problem:
t1.property_id = t2.property_id
t1.property_id = 1
t2.property_id = 2
Which means : 1 = 2.
If I understand well, you're looking for products which have :
a property_id = 1 set
a property_id = 2 set
a value superior to $a if property_id = 1 exists
a value superior to $c if property_id = 2 exists
a value inferior to $b if property_id = 1 exists
a value inferior to $d if property_id = 2 exists
I think you're looking for this request :
SELECT product_id
FROM v
JOIN ppv as t1 ON v.product_id = t1.product_id AND t1.property_id = 1
JOIN ppv as t2 ON v.product_id = t2.product_id AND t2.property_id = 2
WHERE v.value > GREATEST($a, $c)
AND v.value < LEAST($b, $d)
SELECT `product_id`,
CONVERT(GROUP_CONCAT(v.`property_id`) USING cp1251) as properties
FROM `values` as v INNER JOIN `product_property_values` as ppv
ON ppv.value_id = v.id
WHERE
(v.`property_id` = 1 and v.value >= 2500000 and v.value <= 3000000 )
or
(v.`property_id` = 2 and v.value >= 1 and v.value <= 3 )
GROUP by product_id
HAVING LOCATE('1', properties) and LOCATE('2', properties)
Th result:
test 1
v.`property_id` = 1 and v.value >= 2500000 and v.value < 3000000
v.`property_id` = 2 and v.value >= 1 and v.value <= 2
product_id properties
Empty
test2
v.`property_id` = 1 and v.value >= 2550000 and v.value < 3000000
v.`property_id` = 2 and v.value >= 1 and v.value <= 4
product_id properties
2 2,1
test3
v.`property_id` = 1 and v.value >= 2000000 and v.value < 3000000
v.`property_id` = 2 and v.value >= 1 and v.value <= 4
product_id properties
1 1,2
2 2,1
It's OK!

Tuning Slow Performing Queries

I have a query which is taking too long to execute.
I used database tuning advisor to check this query and it suggested some missing indexes and statistics. The problem is I can't create missing index and statistics on those tables because it will slowdown insert/update and affect other scripts. They can't sacrifice their scripts performance because of my query.
Without the help of DTA or disturbing other scripts how do I have to tune my query? Can i break it into small pieces? If so, how?
INSERT INTO #val
SELECT lid.orgid,
lid.periodid,
lid.sourceid,
lid.statementtypecode,
lid.financialsbucketid,
lid.statementcurrencycodeiso,
lid.lineitemid,
lll.financialconceptidglobal,
lid.physicalmeasureid,
CASE
WHEN EXISTS(SELECT TOP 1 '1'
FROM trf.dbo.lineitemfundbdescription LIFD(nolock)
WHERE lll.orgid = lifd.orgid
AND lll.lineitemid = lifd.lineitemid) THEN
(SELECT lifd.lineitemshortdescription
FROM trf.dbo.lineitemfundbdescription LIFD(nolock)
WHERE lll.orgid = lifd.orgid
AND lll.lineitemid = lifd.lineitemid)
ELSE lll.lineitemname
END AS LineItemName,
( CASE
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND
lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 1 ) THEN
lid.lineiteminstancevalue *
cds.dbo.Exrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso, p.periodenddate)
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 0
AND p.periodlengthunitcode = 'M' ) THEN lid.lineiteminstancevalue
*
cds.dbo.Getaveragefxrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso,
Dateadd("MONTH", -p.periodlength, p.periodenddate), p.periodenddate)
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 0
AND p.periodlengthunitcode = 'W' ) THEN lid.lineiteminstancevalue
*
cds.dbo.Getaveragefxrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso,
Dateadd("WEEK", -p.periodlength, p.periodenddate), p.periodenddate)
ELSE lid.lineiteminstancevalue
END ) AS LineItemInstanceValue,
( CASE
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 1 ) THEN
lid.adjustedforcorporateactionvalue *
cds.dbo.Exrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso, p.periodenddate)
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 0
AND p.periodlengthunitcode = 'M' ) THEN
lid.adjustedforcorporateactionvalue
*
cds.dbo.Getaveragefxrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso,
Dateadd("MONTH", -p.periodlength, p.periodenddate), p.periodenddate)
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 0
AND p.periodlengthunitcode = 'W' ) THEN
lid.adjustedforcorporateactionvalue
*
cds.dbo.Getaveragefxrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso,
Dateadd("WEEK", -p.periodlength, p.periodenddate), p.periodenddate)
ELSE lid.adjustedforcorporateactionvalue
END ) AS AdjustedForCorporateActionValue,
lid.reportedcurrencycodeiso,
lid.xbrlelementid,
xbrlele.xbrlelementname,
Cast(NULL AS CHAR(3)),
Cast(NULL AS DATETIME),
Cast(NULL AS DATETIME),
Cast(NULL AS CHAR(1)),
Cast(NULL AS DATETIME),
Cast(NULL AS SMALLINT),
src.dcn,
src.docformat,
lid.asreporteditemid,
ari.docbyteoffset,
ari.docbytelength,
ari.bookmark,
ari.itemdisplayednegativeflag,
ari.itemscalingfactor,
ari.itemdisplayedvalue,
ari.reportedvalue,
ari.reporteddescription,
ari.editeddescription,
src.documentid,
lid.isderived,
lid.statementsectioncode,
IsMissMatchPhysicalMeasureID =0,
lid.istotal,
lid.isexcludedfromstandardization,
si.isdetailed AS IsDetailedSection,
si.ispreliminary AS IsPreliminary,
IsCreditSection =Cast(NULL AS BIT),
IsCreditFCC =Cast(NULL AS BIT),
si.isproforma,
lll.instrumentndaid,
InterimTypeID = CASE p.periodicitycode
WHEN 'A' THEN 0
WHEN 'S' THEN 2
WHEN 'T' THEN 3
WHEN 'Q' THEN 4
END,
si.isnotcomparabletopriorperiod,
si.isfundbspecial,
si.isderived AS IsDerivedSI,
lid.systemderivedtypecode
--FBLog.tasktypeid,
--FBLog.systemstartdatetime,
--FBLog.issplit
FROM trf.dbo.lineiteminstance LID(nolock)
--INNER JOIN #fundbbackwardlog FBLog
-- ON FBLog.orgid = lid.orgid
-- AND FBLog.periodid = lid.periodid
-- AND FBLog.sourceid = lid.sourceid
-- AND FBLog.statementtypecode = lid.statementtypecode
-- AND FBLog.financialsbucketid = lid.financialsbucketid
-- AND FBLog.statementcurrencycodeiso =
-- lid.statementcurrencycodeiso
-- AND lid.asreporteditemid IS NOT NULL
-- AND lid.lineiteminstanceasreporteditemid IS NULL
INNER JOIN trf.dbo.statementinstance SI(nolock)
ON lid.orgid = si.orgid
AND lid.periodid = si.periodid
AND lid.sourceid = si.sourceid
AND lid.statementtypecode = si.statementtypecode
AND lid.financialsbucketid = si.financialsbucketid
AND lid.statementcurrencycodeiso = si.statementcurrencycodeiso
INNER JOIN trf.dbo.period P(nolock)
ON lid.orgid = p.orgid
AND lid.periodid = p.periodid
INNER JOIN trf.dbo.lineitem LLL(nolock)
ON lll.orgid = lid.orgid
AND lll.lineitemid = lid.lineitemid
INNER JOIN trf.dbo.financialconcept FC(nolock)
ON lll.financialconceptidglobal = fc.financialconceptid
LEFT OUTER JOIN trf.dbo.xbrlelement XBRLEle(nolock)
ON lid.xbrlelementid = xbrlele.xbrlelementid
INNER JOIN trf.dbo.asreportedinstance ARI(nolock)
ON lid.orgid = ari.orgid
AND lid.sourceid = ari.sourceid
AND lid.asreporteditemid = ari.asreporteditemid
INNER JOIN trf.dbo.[source] SRC(nolock)
ON src.orgid = ari.orgid
AND src.sourceid = ari.sourceid
WHERE ari.reportedvalue IS NOT NULL --AND SRC.DCN > '' --AND SRC.DocFormat > '' --AND ARI.BookMark > ''
Try to remove functions called in the query like : Exrate() and Getaveragefxrate().
Also change the case statement, where you are using subquery as following.
In the end of the query, use
left outer join trf.lineitemfundbdescription lifd
on lll.orgid = lifd.orgid and lll.lineitemid = lifd.lineitemid
and then the case will be changed to
case
when lifd.orgid is null then lll.lineitemname
else lifd.lineitemshortdescription End As LineItemName
It will fine tune your query to a level and gives you a correct execution plan and advice accordingly.
Remember that execution plan does not show the plan of user defined functions called with in the query.

MySQL IF Result Count 0 Return Message

I need the following query to return a message, such as "No Result" if the Record Count = 0.
set #ID_CARTERA = 1;
select
LEFT(A.F_ANOTRIMESTRE, 4 ) Year,
RIGHT(A.F_ANOTRIMESTRE, 2 ) Quarter,
ROUND ( A.POR_RENTABILIDAD, 2 ) Quarterly_Yield
from dr_rent_carteras_trimestres A
where A.ID_CARTERA = #ID_CARTERA
And (LEFT(A.F_ANOTRIMESTRE, 4 ) = ( select MAX(left(F_ANOTRIMESTRE, 4 ) ) - 0
from dr_rent_carteras_trimestres
where ID_CARTERA = #ID_CARTERA )
and
RIGHT(A.F_ANOTRIMESTRE, 2 ) = 12)
you can trick the system like this:
generate a query to return COUNT(*). This will always return a row, even if there are zero rows to count
Left join your main query with the COUNT(*) query. Use Case statement to replace the results with "No Results".
So, the resulting query will look like (assumption - the main query returns zero or one record only - thus there is no ON clause in the LEFT JOIN!!!!):
set #ID_CARTERA = 1;
select
CASE cnt WHEN 0 THEN "No Results" ELSE Year END,
Quarter,
Quarterly_Yield
FROM
(select count(*) AS cnt
from dr_rent_carteras_trimestres A
where A.ID_CARTERA = #ID_CARTERA
And (LEFT(A.F_ANOTRIMESTRE, 4 ) = ( select MAX(left(F_ANOTRIMESTRE, 4 ) ) - 0
from dr_rent_carteras_trimestres
where ID_CARTERA = #ID_CARTERA )
and
RIGHT(A.F_ANOTRIMESTRE, 2 ) = 12) ) cnt_tbl
LEFT JOIN
( select
LEFT(A.F_ANOTRIMESTRE, 4 ) Year,
RIGHT(A.F_ANOTRIMESTRE, 2 ) Quarter,
ROUND ( A.POR_RENTABILIDAD, 2 ) Quarterly_Yield
from dr_rent_carteras_trimestres A
where A.ID_CARTERA = #ID_CARTERA
And (LEFT(A.F_ANOTRIMESTRE, 4 ) = ( select MAX(left(F_ANOTRIMESTRE, 4 ) ) - 0
from dr_rent_carteras_trimestres
where ID_CARTERA = #ID_CARTERA )
and
RIGHT(A.F_ANOTRIMESTRE, 2 ) = 12) ) main_tbl
The same thing can be accomplished with UNION. Ask in the comments if you wish me to show how