Select all from DB where the content has defined - mysql

I am trying to retrieve a list of database records which have specific 'interest codes' inside of the 'custom_fields' table. So for example right now there is 100 records, I need the Name, Email and Interest Code from each of those records.
I've tried with the following statement:
SELECT * FROM `subscribers` WHERE list = '27' AND custom_fields LIKE 'CV'
But with no luck, the response was:
MySQL returned an empty result set (i.e. zero rows). ( Query took 0.0003 sec )
You can see in this screenshot that at-least two rows have 'CV' inside custom_fields. Whilst within the database it's not called 'Interest Code', that's what they are so therefore why I am referencing it in this way.

You need to enclose your "search string" inside some wildcards:
select * from subscribers where list=27 and custom_fields like '%CV%';
The % wildcard means "zero or more chacarcters at this position". The "_" wildcard means "a character in this position". Please read the reference manual on the topic. Also, you may want to read about regular expressions in MySQL for more complex string comparissons.

Related

Using a MySQL Select with a RegEx Expression embedded within a String

I am using PHP to access a mysql database field that contains up to 2500 characters per record.
I want to build queries that will return only the records that include a single word, like 'taco'.
Sometimes, however, the user will need to search for a word like 'jalapeno'. Except that jalapeno may exist in the database as 'jalapeno' or as 'jalapeño'. The query should return both instances.
As a further complication, the user may also need to search for a word like 'creme', which may appear as 'creme' or 'créme', but never as 'crémé'.
It seems like I should be able to construct something that uses a replace, and then a Regular Expression, so that the letter 'n' is always replaced with '[n|ñ]', and then search for a string with an embedded Regular Expression like this: 'jalape[n|ñ]o'. Except that does not work. MySQL treats the RegEx syntax as literals.
None of the following return the results that I am looking for:
SELECT id, record FROM table WHERE record like '%jalapeno%';
SELECT id, record FROM table WHERE record REGEXP 'jalapeno';
SELECT id, record FROM table WHERE record REGEXP 'jalape[n|ñ]o';
SELECT id, record FROM table WHERE REGEXP_LIKE(record, 'jalape[n|ñ]o', 'im');
Additionally, I can use PHP to do a replacement of the potential characters, but I end up with stuff like this:
SELECT id, record FROM table WHERE (record like '%creme%' || record like '%crémé%');
I would be Ok with a search like this, but it seems overly complicated to construct programmatically:
SELECT id, record FROM table WHERE (record like '%creme%' || record like '%crémé%' || record like '%cremé%' || record like '%cremé%' );
Is there a MySQL method that provides a REGEX 'OR' to be embedded within a String?
Maybe something like this:
SELECT id, record FROM table WHERE record like '%cr[e|é]m[e|é]%' ;
Or is there another solution that would not require the construction of an excessively convoluted SQL Statement?
Thanks for anyone who spent time trying to figure this out.
As I commented above, REGEXP_LIKE() does not appear to be a valid MySQL function for the current release.
Here is my solution; Note that this works for MySQL 5.7.x.
SELECT id, record FROM table WHERE record RLIKE 'jalape(n|ñ)o';

Attempting find an embedded string in database with mysql

I'm attempting to query our database to find specific types of transactions with unique parameters.
There are multiple formats and I'm looking to get the transactions with the -Q/ parameter.
BCR*DEVSTS
BCR*1150
BCR*1150/28AUG
BCR*DEVSTS-Q/28AUG
BCR*DEV-Q/28AUG
I'm able to find the BCR transactions but due to memory constraints I can only get the first 10k rows and they don't have the -Q/ parameter. I'm trying to create a query that will only select the required transactions.
I used the following to query for the basis transaction:
select *
from transaction_200827
where reqresponse= 'Q' and message rlike '^BCR.*'
I've reviewed multiple websites but haven't been able to find an example of this scenario. I've tried variations on the examples provided and haven't been successful:
select * from transaction_200827 where reqresponse= 'Q' and message rlike '^BCR(Q/).*'
select * from transaction_200827 where reqresponse= 'Q' and message rlike '^BCR%Q/%.*'
I'm fairly new to building queries and would appreciate any guidance or direction for generating this type of query.
You're mixing regexp and LIKE patterns. Use either
message LIKE 'BCR%-Q/%'
or
message RLIKE '^BCR.*-Q/'
You're also missing the - before Q in your patterns.
There's no need to add .* to the end of the regexp -- RLIKE succeeds when the regexp matches anywhere in the string, it doesn't have to match the entire string (the ^ anchor forces it to match starting from the beginning, but there's no $ anchor extending it to the end).
If the column has an index, I recommend using LIKE -- in my experience, RLIKE doesn't take advantage of indexes. Either way, the index will only be used for matching the BCR at the beginning, the rest requires scanning all the values with that prefix.

MySQL different counts between "where =" and "where like"

1. select count(*) from tableX where code = "XYZ";
2. select count(*) from tableX where code like "%XYZ";
Result for query 1 is 18734. <== Not Correct
Result for query 2 is 93003. <== Correct
We know that query 2's count is correct based on independent verification.
We expect these two queries to have the exact same count for each because we know that no rows in tableX have a code that ends with "XYZ", so the wildcard at the beginning shouldn't affect the query.
Why would these queries produce different counts?
We have already researched the differences between "=" comparison and "like" string comparison, but based on all our verification checks, we still don't understand why this would give us different counts
We have confirmed the following:
There are no leading or trailing characters in the "code" field
There are no hidden characters (tried all found here: How can I find non-ASCII characters in MySQL?)
The collation is "utf8_unicode_ci"
We are using MySQL version 5.5.40-0ubuntu0.12.04.1.
Try this in order to get your answer:
SELECT code
FROM tableX
WHERE code LIKE "%XYZ"
AND code <> "XYZ"
LIMIT 10
My guess is that some of your codes end with a lowercase xyz, and since LIKE is case-insensitive, it matched these where = did not.
where code = "XYZ"; gives exact match whereas where code LIKE "%XYZ"; includes partial match as well. In your case, there could be an extra space present which is giving wrong count. Consider trimming before comparing like
where UPPER(TRIM(code)) = 'XYZ';
We restarted the server that the database resides on, we re-ran the queries, and now they all are producing the expected, correct results...
We'll have to look into possibilities for why this "fixed" the issue.

Show Fields but with content

i'm trying to show fields names on a combobox, but I need only those that are not null or have blank spaces.
I all ready have the field names with this query:
SHOW FIELDS FROM model WHERE type LIKE 'varchar(15)'
Any idea about how can i do this?
Update:
I'm working with an old database who is poorly designed. I attached an image:Database Screenshot This is a tire sizes database, so i need to get the years by model who has the size captured to show them in a combo box.
You can use your current query to get the "candidate" fields, but (short of some very complicated dynamic sql) you'll need to build a separate query to determine which candidates are pertinent. Generically, something like:
SELECT SUM(IF(field1 REGEXP '[a-zA-Z0-9.]+', 1, 0) > 0 AS showField1
, SUM(IF(field2 REGEXP '[a-zA-Z0-9.]+', 1, 0) > 0 AS showField2
, ...
FROM theTable
;
Depending on what you consider "has values" the regexp string may need adjusted; learn more here: http://dev.mysql.com/doc/refman/5.7/en/regexp.html
If the table is huge (large number of rows), you may be better off querying on each field separately like this (the one above will be looking at the whole table without some sort of WHERE to reduce the rows examined):
SELECT 1 FROM theTable WHERE fieldX REGEXP '[a-zA-Z0-9.]+' LIMIT 1;
Treating having a query result as "yes" and no result as "no content".

sql server select where breaks with field containing apostrophe

I have set up a job to run reports and uses multiple tables with joins. I am joining two tables on a string field and if the field contains an apostrophe, it does not return any matches. This is weird and not sure why is is happening now and never before. I am perhaps not identifying the exact cause but will appreciate any help here:
Example query: "today's deals"
SET #TITLE = (SELECT MAX(B.DATEADDED) as 'td','',
(C.CLIENT + CHAR(10) + B.CLIENTKEY) as 'td','',
B.BADQ as 'td','',A.FULLQ as 'td','', B.BADERROR as 'td',
''
FROM BADQUERY AS B
LEFT JOIN QDATA AS A ON B.BADQ = A.QUERYT
LEFT JOIN Clients AS C ON C.clientKey = B.clientKey
WHERE DATEDIFF(minute,CAST(B.DATEADDED as datetime),GETDATE())<=420 AND
DAY(GETDATE()) = DAY(B.DATEADDED)
GROUP BY B.BADT,A.FULLQ, B.CLIENTKEY,C.CLIENT, B.BADERROR
FOR XML PATH ('tr'), ELEMENTS XSINIL)
For some reason A.FULLQ is being returned as NULL. When I do it separately with just a query the result set is also null but I know the matching record in QDATA as A is in the table. So if it is the query with apostrophe how can get the matching field or is sql server matching the data and something else is wrong.
If I try and match with a like it returns results but this is not accurate.
If B.BADQ and A.QUERYT don't exactly match, you won't get any records back. The fact that it works with a LIKE makes me wonder whether one of them has additional characters, either before or after the matching data (depending on how you set up the LIKE).
Michael Green is right, below, that trailing blanks by themselves don't prevent a match, but, depending on where your data originates, you might have some other character (such as an embedded CHAR(0) or a TAB character) that doesn't appear when you view the data in the record but which is enough to prevent the records from matching. You might use the CHECKSUM() function on the two strings to verify that they do represent the same data.
Another, similar possibility is that if there is a string of blanks in the values (something like "A, B, ' '") the number of blanks might be different between the two instances. They'd look the same in HTML (which it looks like you're generating) but they'd be different in reality and be enough to prevent a match.
Finally, the fact that you're generating XML and observing trouble with apostrophes made me think of this: if the content of an XML tag has an apostrophe, it will be converted to &apos;. That ought to affect only the output, not the functioning, of the query, but I don't know what your data actually looks like.