Mysql use parsed column from SELECT in WHERE condition - mysql

How can I do something like this:
SELECT DID, DNumbers, CONCAT(SUBSTRING_INDEX(DNumbers, " - ", 1), ", ") AS DNumbers_Parsed
FROM Test
WHERE DNumbers_Parsed LIKE '%, 1,%' AND DNumbers_Parsed LIKE '%, 5,%'
This gives an error saying column DNumbers_Parsed not found. I know I can just use the same parsing thing for each condition but is it possible to only do it once and then use it in conditions?

Generally speaking, you can't use derived fields in a where clause, as the value of the derived field MAY not be available yet at the time the where filter is being applied (e.g. aggregate function results).
Try using a HAVING instead:
SELECT ...
FROM ...
HAVING DNumbers_Parsed LIKE ...
HAVING is applied just before the results are sent to the client, after all aggregate operations/field value derivations have been completed.
and note that your code above has a typo: AN DNumbers_....

well the having clause posted by Marc B is a good solution.. even though having is generally slow... another way you could try it is in a sub query so that way the data is already returned from the server.
SELECT *
FROM(
SELECT DID, DNumbers, CONCAT(SUBSTRING_INDEX(DNumbers, " - ", 1), ", ") AS DNumbers_Parsed
FROM Test
)t
WHERE t.DNumbers_Parsed LIKE '%, 1,%' AN t.DNumbers_Parsed LIKE '%, 5,%'

Related

Select * from Select

Its very weird situation I know, nut I have got myself into it somehow. I have to connect to some other system service by passing some parameters in url.
In their service they are creating some query using parameter I pass.
For my case I have to pass 'Select' as a parameter name which is actually some class name on their side. So they end up in creating query as Select * from select
and some condition.
On execution I am getting error response as:
'There was a syntax error in a SQL query or filter expression at line
1, position 186. Saw \"Select\" but expected
'..SQL: \"SELECT col1, col2 FROM Select AS D where
some condition.
Can somebody help me on this.
Since Select is reserved word, you have to escape it by enclosing in backticks characters in order for MySQL to process your query:
select * from `select`
Its recommended not to use MySQL reserved keywords.. but if its necessary there is a solution..
Use this, it will work for you :
select * from yourdatabasename.select

Mysql Query Request

Straight to the point and this might be very simple for some of you.
I have a simple SELECT query (select description from table) which produces all i want like below :
- testword123
- testword875
- myjob1 45
- myjob is 544
What i need is to have as a result :
- testword
- myjob
I can use a SELECT distinct LEFT(description,8) which works fine, but the problem is not ALL 'description' have the same number of words :-(
So basically, what i want is retrieve ONLY the letters from the 'description' result set.
Thanks!!
R
SELECT distinct LEFT(description, charindex(' ', description) - 1)
Depending on your implementation, it might be possible to declare 'description' as a variable beforehand so you don't have to type it twice in the same query.
There are two decisions:
1) Handle each decription in PHP
or
2) Handle user input before writing it to DB. Add field to table as index of first not letter symbol and then use it in LEFT mysql function
Thanks "undefined_variable" - Your solution "stackoverflow.com/questions/11134452/…; was the correct one!! (y) (with a little bit of tweaking, this helped A LOT) A+++

Using REPLACE() in MySQL SELECT

I apologise in advance for asking what I'm sure will prove to be a very simple question.
I have a MySQL (5.5) database that includes, amongst other things, a field for telephone numbers. I'm trying to create a statement that will search that field, stripping out any spaces. So searching for '0208' will return '020 8', '02 08', '0 208', ' 0208', etc.
And this is in Delphi XE2, in case that makes a difference.
'SELECT * FROM sales_ledger WHERE REPLACE(telephone, " ", "") LIKE "%' + SearchEdit.Text + '%"'
...gives me an error...
Invalid filter in WHERE clause
...and...
'SELECT REPLACE(telephone, " ", "") FROM sales_ledger WHERE REPLACE(telephone, " ", "") LIKE "%' + SearchEdit.Text + '%"'
...gives me...
Invalid field name. General SQL error. Column not found.
...and I do actually need all fields returned anyway.
May I ask for some assistance in correcting the syntax please. If you need more information, don't hesitate to ask. Thanks very much for your time.
EDIT: One potentially critical piece of information I missed out. The table is actually a Sage database that I'm accessing through ODBC. As nothing I try is working that may well be the root problem. Apologies for not saying that earlier.
Your Query Seems Working Fine see the demo
First try this query to you DB Client
SELECT * FROM sales_ledger
WHERE REPLACE(telephone, " ", "") LIKE "%0208%"
EDIT:
if you query is still not working. fellow step by step process.
try to run a simple select query (SELECT * FROM sales_ledger)
if the first query run try adding simple where condition.
so step by step you can make your query similar to original one and find where is the actual error from.
Try this ::
SELECT
REPLACE(telephone,' ', '') as replacedColumn
FROM sales_ledger
WHERE REPLACE(telephone,' ', '') LIKE '%"+ SearchEdit.Text +"%'"
OR
Select temp1.*
from
(
SELECT
REPLACE(telephone,' ', '') as replacedColumn
FROM sales_ledger
) as temp1
WHERE temp1.replacedColumn LIKE '%"+SearchEdit.Text+"%'"

How do I remove slashes during a select statement

Please I am new. I am performing an insert select and I want to remove the slashes in a particular field say field b at the select portion of the query.
eg. insert into mytable(a,b,c) select a, stripslashes(b),c from mysecondtable;
Please help.
you can use REPLACE like this:
insert into mytable(a,b,c)
select a, REPLACE(b, '\\', '\') as b, c
from mysecondtable;
The REPLACE expression might have to be refined, but I hope this gets you started.
You can use MySQL String functions, e.g. replace.
Also consider sanitizing or preparing any input to the SELECT in the calling application before you execute the query.
use the SUBSTR function of mysql or do something like this:
"insert into table set value = " . stripslashes('whatever')
Are you doint this with PHP? Then a simple $fieldB = strip_slashes($_POST['b']); should do. You should then use $fieldB in your query.

Combine 'like' and 'in' in a SqlServer Reporting Services query?

The following doesn't work, but something like this is what I'm looking for.
select *
from Products
where Description like (#SearchedDescription + %)
SSRS uses the # operator in-front of a parameter to simulate an 'in', and I'm not finding a way to match up a string to a list of strings.
There are a few options on how to use a LIKE operator with a parameter.
OPTION 1
If you add the % to the parameter value, then you can customize how the LIKE filter will be processed. For instance, your query could be:
SELECT name
FROM master.dbo.sysobjects
WHERE name LIKE #ReportParameter1
For the data set to use the LIKE statement properly, then you could use a parameter value like sysa%. When I tested a sample report in SSRS 2008 using this code, I returned the following four tables:
sysallocunits
sysaudacts
sysasymkeys
sysaltfiles
OPTION 2
Another way to do this that doesn't require the user to add any '%' symbol is to generate a variable that has the code and exceute the variable.
DECLARE #DynamicSQL NVARCHAR(MAX)
SET #DynamicSQL =
'SELECT name, id, xtype
FROM dbo.sysobjects
WHERE name LIKE ''' + #ReportParameter1 + '%''
'
EXEC (#DynamicSQL)
This will give you finer controller over how the LIKE statement will be used. If you don't want users to inject any additional operators, then you can always add code to strip out non alpha-numeric characters before merging it into the final query.
OPTION 3
You can create a stored procedure that controls this functionality. I generally prefer to use stored procedures as data sources for SSRS and never allow dynamically generated SQL, but that's just a preference of mine. This helps with discoverability when performing dependency analysis checks and also allows you to ensure optimal query performance.
OPTION 4
Create a .NET code assembly that helps dynamically generate the SQL code. I think this is overkill and a poor choice at best, but it could work conceivably.
Have you tried to do:
select * from Products where Description like (#SearchedDescription + '%')
(Putting single quotes around the % sign?)
Dano, which version of SSRS are you using? If it's RS2000, the multi-parameter list is
not officially supported, but there is a workaround....
put like this:
select *
from tsStudent
where studentName like #SName+'%'
I know this is super old, but this came up in my search to solve the same problem, and I wound up using a solution not described here. I'm adding a new potential solution to help whomever else might follow.
As written, this solution only works in SQL Server 2016 and later, but can be adapted for older versions by writing a custom string_split UDF, and by using a subquery instead of a CTE.
First, map your #SearchedDescription into your Dataset as a single string using JOIN:
=JOIN(#SearchedDedscription, ",")
Then use STRING_SPLIT to map your "A,B,C,D" kind of string into a tabular structure.
;with
SearchTerms as (
select distinct
Value
from
string_split(#SearchedDescription, ',')
)
select distinct
*
from
Products
inner join SearchTerms on
Products.Description like SearchTerms.Value + '%'
If someone adds the same search term multiple times, this would duplicate rows in the result set. Similarly, a single product could match multiple search terms. I've added distinct to both the SearchTerms CTE and the main query to try to suppress this inappropriate row duplication.
If your query is more complex (including results from other joins) then this could become an increasingly big problem. Just be aware of it, it's the main drawback of this method.