Merge two MySQL queries and replace result - mysql

I want to find a way to use one query where I am replacing the LineUps.DIG output when it = Y. I'm wanting to mark as an asterisk in html. maybe it's better to do this on the front end vs sql query.
Fist query works and returns the data
$stmt = $conn->prepare("SELECT distinct Channel_LineUps.channel, Channel_LineUps.description, Channel_LineUps.Tier, LineUps.HD, LineUps.DIG FROM Channel_LineUps, LineUps WHERE (LineUps.Market_ID = Channel_LineUps.Market_ID AND Channel_LineUps.Market_ID = 28) ORDER BY Channel_LineUps.Tier ASC");
Second query is where i have the replace but am not sure how to merge with above query.
SELECT DIG,REPLACE(DIG,"Y","*") as output FROM LineUps WHERE DIG="Y");

I think CASE WHEN is what you are looking for:
$sql = <<<SQL
SELECT DISTINCT Channel_LineUps.channel, Channel_LineUps.description,
Channel_LineUps.Tier, LineUps.HD,
CASE LineUps.DIG WHEN "Y" THEN REPLACE(LineUps.DIG, "Y", "*") ELSE LineUps.DIG END
FROM Channel_LineUps, LineUps
WHERE (LineUps.Market_ID = Channel_LineUps.Market_ID
AND Channel_LineUps.Market_ID = 28)
ORDER BY Channel_LineUps.Tier ASC
SQL;
$stmt = $conn->prepare($sql);
You can also directly replace line 4 above with:
CASE LineUps.DIG WHEN "Y" THEN "*" ELSE LineUps.DIG END
as you know its value for sure.

Related

Error in nested case query using SQL

Trying to convert below query into SQL, query works fine on MySQL. Problem seems to be the CASE WHEN area field I get same error.
show Msg 102, Level 15, State 1, Line 44 Incorrect syntax near '='.
Msg 156, Level 15, State 1, Line 47 Incorrect syntax near the keyword
'AND'. Msg 156, Level 15, State 1, Line 49 Incorrect syntax near the
keyword 'ELSE'.
WHEN T.[StatusID] = 3
THEN
CASE WHEN (((SELECT COUNT(TA1.[Approver_ID]) FROM [QESTORM].[dbo].[CR_TicketApproval] TA1
INNER JOIN [QESTORM].[dbo].[CR_ControlFlow_SubRoute] CFSR1 ON TA1.[SubRoute_ID] = CFSR1.[ID]
WHERE TA1.[Ticket_ID]= #iTkID AND TA1.Active=1 AND CFSR1.Active=1 AND CFSR1.[Sequence] =(SELECT CFSR2.[Sequence] FROM [QESTORM].[dbo].[CR_Ticket] T2 INNER JOIN [QESTORM].[dbo].[CR_ControlFlow_SubRoute] CFSR2 ON T2.[SubRouteID] = CFSR2.[ID]
WHERE T2.[ID] = #iTkID))<(SELECT COUNT(DISTINCT CFSR1.[ID])FROM [QESTORM].[dbo].[CR_Ticket] AS T1 INNER JOIN [QESTORM].[dbo].[CR_ControlFlow_Route] AS CFR1 ON T1.[FormID] = CFR1.[FormID] INNER JOIN [QESTORM].[dbo].[CR_ControlFlow_SubRoute] AS CFSR1 ON CFR1.[ID] = CFSR1.[RouteID]
WHERE CFR1.[Active] = 1 AND CFSR1.[Active] = 1 AND T1.[ID] = #iTkID AND CFSR1.[Category] = 1 AND CFSR1.[Sequence] = ( SELECT CFSR2.[Sequence] FROM [QESTORM].[dbo].[CR_Ticket] AS T2 INNER JOIN [QESTORM].[dbo].[CR_ControlFlow_SubRoute] AS CFSR2 ON T2.[SubRouteID] = CFSR2.[ID]
WHERE T2.[ID] = #iTkID))))
THEN
CASE WHEN ((SELECT COUNT(1) FROM [QESTORM].[dbo].[CR_TicketApproval] WHERE [Ticket_ID]=#iTkID And [Active]=1) = 0)
THEN
--ERROR SHOW HERE => ((T.[AuditUser_ID] = '444' OR T.[AuditUser_ID] IS NULL) AND (nx.actor = 2 OR appSameSeq.NTLogin=in_NTLogin)
AND nx.actor=3
AND srSameSeq.subRouteID NOT IN (SELECT subRouteID FROM [QESTORM].[dbo].[CR_TicketApproval] WHERE [Ticket_ID]=#iTkID AND Active=1 )
AND appSameSeq.NTLogin=in_NTLogin
AND nx.actor=3 AND srSameSeq.subRouteID NOT IN (SELECT subRouteID FROM [QESTORM].[dbo].[CR_TicketApproval] WHERE [Ticket_ID] = #iTkID AND Active = 1)
ELSE 0
END
I'll toss my hat in the ring.
There may be more than one thing wrong with that SQL statement. What I'll point out is this:
CASE WHEN ((SELECT COUNT(1) FROM [QESTORM].[dbo]. [CR_TicketApproval] WHERE [Ticket_ID]=#iTkID And [Active]=1) = 0)
THEN
--ERROR SHOW HERE => ((T.[AuditUser_ID] = '444' OR T.[AuditUser_ID] IS NULL) AND (nx.actor = 2 OR appSameSeq.NTLogin=in_NTLogin)
AND nx.actor=3
AND srSameSeq.subRouteID NOT IN (SELECT subRouteID FROM [QESTORM].[dbo].[CR_TicketApproval] WHERE [Ticket_ID]=#iTkID AND Active=1 )
AND appSameSeq.NTLogin=in_NTLogin
AND nx.actor=3 AND srSameSeq.subRouteID NOT IN (SELECT subRouteID FROM [QESTORM].[dbo].[CR_TicketApproval] WHERE [Ticket_ID] = #iTkID AND Active = 1)
ELSE 0
END
Are you trying to evaluate a conditional expression, and return the result as a 1 or 0, as if it were a Boolean expression in a programming language?
That doesn't work in TSQL. This kind of expression evaluation:
SET #value = (1 > 0)
... will produce an error. You can't evaluate a conditional expression: you can only use it in a test, like in a WHERE, HAVING, or WHEN clause.
So, if that's what you're doing, you might do better to wrap your conditional evaluation in yet another CASE statement, like this:
THEN
CASE WHEN {complex conditional statement}
THEN 1
ELSE 0
END
ELSE
0
END
One other thing: this is an extremely complex query statement! I haven't analyzed it enough to see whether it could be simplified, but I'd suggest that you do so, with an eye toward using Common Table Expressions in place of some of your subqueries. This can make the query a lot easier to understand (and debug).
We are missing the complete query but it looks like you are opening too many parentheses.
If you look at the line where your error is shown:
((T.[AuditUser_ID] = '444' OR T.[AuditUser_ID] IS NULL) AND (nx.actor = 2 OR appSameSeq.NTLogin=in_NTLogin)
You are opening 2 parentheses but only close one.
That is why you get the error near else because you need to close that second parentheses before you can have an else
So you would need either
((T.[AuditUser_ID] = '444' OR T.[AuditUser_ID] IS NULL) AND (nx.actor = 2 OR appSameSeq.NTLogin=in_NTLogin))
or
(T.[AuditUser_ID] = '444' OR T.[AuditUser_ID] IS NULL) AND (nx.actor = 2 OR appSameSeq.NTLogin=in_NTLogin)
on that line
It looks like you don't have a 'return value' for your case statement on that specific line.
When you flatten your CASE WHEN statement you have something like this:
CASE WHEN <something> THEN
CASE WHEN <something else> THEN
CASE WHEN <something else again> THEN
-- THEN WHAT ?
ELSE
0
END
END
END
Instead of putting a value on the --THEN WHAT spot, you put another conditional statement. You have to select a value here.

Use Multiple keywords with mysql Like

I want to write mysql query to display all records if text field value = "All" or else display records similar to keyword value. I have written code below to just to give an idea.
if (keyword = 'All' )
select * from ItemMain
else if (keyword like %itemname%)
select * from ItemMain
Ok, assuming PHP as the front-end language you can put it all in one query like this (forgive the curly braces; I'm never sure when they're needed or not so I tend to over-use them):
$query = <<< ENDSQL
SELECT *
FROM ItemMain
WHERE ('{$keyword}' = 'All') OR (your_textfield like '%{$keyword}%')
ENDSQL;
... execute the query
But really I'd go with the suggestion from #cjg and use two different queries:
$query = "";
if ($keyword == 'All') {
$query = "SELECT * FROM ItemMain";
} else {
$query = "SELECT * FROM ItemMain WHERE your_textfield LIKE '%{$keyword}%'";
}
... execute the query
If itemname is your column name, and your search string parameter replaces the ? in your code. Then your statement should look something like this if you are searching for all itemnames containing your search string:
SELECT *
FROM ItemMain
WHERE ? = 'All' OR itemname LIKE '%?%'
Or this if you are looking for an exact match:
SELECT *
FROM ItemMain
WHERE ? = 'All' OR itemname = ?

Getting all results using where clause

I have a function which takes an argument that is used in where clause
function(string x)-->Now this will create a sql query which gives
select colname from tablename where columnname=x;
Now I want this function to give all rows i.e. query equivalent to
select colname from tablename;
when I pass x="All".
I want to create a generic query that when I pass "All" then it should return me all the rows else filter my result.
Just leave the where condition out.
If you really want it that complicated use
where columnname LIKE '%'
which will only filter nulls.
select colname from tablename
where columnname=(case when #x ="All" then columnname
else #x end)
Try this
select colname from tablename where 1=1
hope the above will work
where 1=1 worked for me, Although where clause was being used all records were selected.
You can also try
[any_column_name]=[column_name_in_LHL]
(LHL=left hand side.)
refer my answer for more details
I had the same issue some time ago and this solution worked for me
select colname from tablename where columnname=x or x = 'ALL'
SELECT * FROM table_name WHERE 1;
SELECT * FROM table_name WHERE 2;
SELECT * FROM table_name WHERE 1 = 1;
SELECT * FROM table_name WHERE true;
Any of the above query will return all records from table.
In Node.js where I had to pass conditions as parameter I used it like this.
const queryoptions = req.query.id!=null?{id : req.query.id } : true;
let query = 'SELECT * FROM table_name WHERE ?';
db.query(query,queryoptions,(err,result)=>{
res.send(result);
}
It's unclear what language you're using for your function, but you have to somehow parse the 'All' prior to getting to sql:
public void query(String param) {
String value = "":
switch (param) {
case 'All':
value = "*";
break;
default:
value = param;
}
String sql = "select colname from tablename where colname="+value;
//make the query
}
If you have to allow 'ALL' to be passed through as the parameter value to your function, then you will need to put some manipulation code in your function to construct your SELECT statement accordingly. I.e. You can detect if the parameter has 'ALL' in it and then omit the WHERE clause from your SQL statement. If a value other than 'ALL' comes through, then you can include the WHERE clause along with the relevant filter value from the parameter.
An example of a piece of code to do this would be;
IF x = 'ALL'
THEN
SELECT COLNAME FROM TABLENAME;
ELSE
SELECT COLNAME FROM TABLENAME WHERE COLUMNNAME = X;
END IF;
Give a conditional check in your code(assuming Java) to append the WHERE clause only when x != 'All'
mySqlQuery = "SELECT colname FROM tablename" +
(x.equals("All") ? "" : "WHERE columnname = "+x);

IF condition in mysql

I have a contact table I wish to query when a certain condition exists. I tried the query below but am getting a syntax error.
SELECT *
FROM contact_details
WHERE contactDeleted` =0
AND IF ( contactVisibility = "private"
, SELECT * FROM contact_details
WHERE contactUserId = 1
, IF( contactVisibility = "group"
, SELECT * FROM contact_details
WHERE contactGroup = 3
)
)
If I'm understanding your question correctly (which is difficult with the lack of info you've provided. Sample datasets and expected outcomes are typically helpful), then I don't believe you need IFs at all for what you want. The following will return contacts that are not deleted and who either have (visibility = "private" and userId = 1) OR (visibility = "group" and group = 3)
SELECT *
FROM contact_details
WHERE contactDeleted = 0
AND (
(contactVisibility = "public")
OR
(contactVisibility = "private" AND contactUserId = 1)
OR
(contactVisibility = "group" AND contactGroup = 3)
)
I am assuming you want to use the IF() function and not the statement which is for stored functions..
Refer to this link for more information on that.
Notice that you have put 2 select statements in there, where the custom return values are supposed to be. So you are returning a SELECT *... now notice that in your upper level sql statement you have an AND.. so you basically writing AND SELECT *.. which will give you the syntax error.
Try using .. AND x IN (SELECT *) .. to find if x is in the returned values.
Let me also list this link to make use of an existing and well written answer which may also applicable to your question.

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