MySQL: SELECT * FROM table WHERE field="some text" doesn't work - mysql

I am trying to INNER JOIN two tables on a text field, but I can't get it to work.
I've backtracked to see if I can identify where my query is falling down.
I've simplified my query to use only one table, to see if I can select data from it based on a text string.
I can't make it work.
I feel like an idiot.
This is so basic, why isn't it doing it?
select * from `my-table`
where myKey = "some-text-data-that-i-copied-from-the-data-in-the-table";
Returns no rows.
"some-text-data-that-i-copied-from-the-data-in-the-table" is in field myKey. I can see it. It's in the table!!!
[if it makes any difference I am most familiar with using an Access front-end and I am porting my "skills" to MySQL because MySQL is just better really.. this seems like the most run of the mill SELECT statement ever and yet it doesn't do anything!]
EDIT:
IMSoP does this help any...
select * from mymathssowlink
where MyMathsResourceKey = 'KS2-Number-Counting and Place Value-NC3-Negative Numbers 1';
EDIT 2:
Diego Marinelli - thanks - this returns data
select * from mymathssowlink
where MyMathsResourceKey like '%KS2%';
EDIT 3:
This works...
select * from mymathssowlink
where MyMathsResourceKey like '%KS2-Number-Counting and Place Value-NC3-Negative Numbers 1%';
EDIT 4:
But this still doesn't...
select * from mymathssowlink
where MyMathsResourceKey = 'KS2-Number-Counting and Place Value-NC3-Negative Numbers 1';
puzzled
Table:
CREATE TABLE `mymathssowlink` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`ObjectiveID` varchar(13),
`MyMathsResourceKey` varchar(100),
PRIMARY KEY (`ID`),
UNIQUE KEY `idnew_table_UNIQUE` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
HOW IT GOT FIXED:
okay very weird but I have fixed the simplified problem now! I remember from my Access days that trailing spaces are the bane of matches and it seems the MySQL is a bit fiddly in this regard to. There was no problem with the data as such but the field MyMathsResourceKey was the last bit of data on each line and so not terminated with a comma. Some lines didn't have any data in that column and so were terminated with a comma rather than the MyMathsResourceKey data. I fixed it by adding a third column to my csv into which i uniformly stuck the string "PLACEHOLDER". I matched this to a column called placeholder in the table receiving the data. Now that the active (2nd column) is always terminated with a comma all the data seems to work. I can't help thinking that this is a bit odd and that MySQL data imports really don't want to be behaving like this... now to try an make my JOIN work, which how this all started!
Thanks to all, especially Rahul for the help.
... and the JOIN Works now...

Going by all the edits in your post and comments; what I feel is, there is extra space present in your column value and so you are not getting the data (since it's not matching the exact string).
So either try like
select * from mymathssowlink
where MyMathsResourceKey
like '%KS2-Number-Counting and Place Value-NC3-Negative Numbers 1%';
(OR)
Use a REPLACE() function to remove all spaces in the field value
select * from mymathssowlink
where REPLACE(MyMathsResourceKey, ' ', '')
= 'KS2-Number-Counting and Place Value-NC3-Negative Numbers 1';
You can as well use TRIM() function if you can guarantee that the spaces are present only in left/right extreme of the string.
select * from mymathssowlink
where TRIM(MyMathsResourceKey)
= 'KS2-Number-Counting and Place Value-NC3-Negative Numbers 1';

You can try Select * from table; and if that works then try select * from table where key like '%some_text%'
It could not be a problem with the sintax but with the query itself.

Related

mysql - search pattern and replace

I have MySQL table wp422_posts and I need to manipulate one type of values in post_name column. Actually, I need to manipulate long value beginning with 4 digits (unique ID) and than text, I need to get the 4 digits and left them there. Could anybody help me, please? I'm new to MySQL. Other values - which do not start with 4 digits and dash has to stay same.
one example of value of post_name
old:
"2147-sprava-uzivatelskych-uctu-databaze-oracle-v-prostredi-autocad-map-3d"
desired
new one: "2147"
How to select correct values in column:
SELECT * FROM `wp422_posts` WHERE `post_name` LIKE "[0-9][0-9][0-9][0-9]%"
it returns empty result, but why?
How to get rid of not needed part?
Thanks relly much for your help.
If you are sure that starting part is always 4 digit number and that is only needed, then you can use this:-
SELECT LEFT(COL_NAME, 4)
FROM `wp422_posts`
Then you can use update statement to update the table. Somthing like:-
UPDATE `wp422_posts`
SET COL_NAME = LEFT(COL_NAME, 4)
Hope this helps!!

Using Like and Concat with Char Type

I have a MySQL statement that is trying to find if the ID of a row (CHAR(36)) is inside of a string.
My statement is :
select * from `options`
where concat('%',`OptionID`,'%')
like '{\"4d519a3d-c99b-11e4-8eda-b8ca3a83b4c8\":\"62.50\"}';
But this fails and doesn't return anything, while this
select * from `options` where
`OptionID`='4d519a3d-c99b-11e4-8eda-b8ca3a83b4c8';
works and returns my row. I thought this was because the ID field was a CHAR field instead of a VARCHAR field so I tried this instead
select * from `options` where
concat('%',cast(`OptionID` as char(38)) ,'%')
like '{\"4d519a3d-c99b-11e4-8eda-b8ca3a83b4c8\":\"62.50\"}';
But that still didn't work, and now I'm lost. I would like to avoid iterating through the json string and creating a set of conditions like
(`OptionID`={$JsonKey[0]} OR `OptionID`={$JsonKey[1]} OR ... )
Since these json strings can get very large, but if that it is the best option because of performance or what I'm trying to do can't be done any other way, then I'll just do it that way instead.
The concept will work, but you're doing it backwards. You need to reverse the fields.
Something like this:
select *
from `options`
where '{\"4d519a3d-c99b-11e4-8eda-b8ca3a83b4c8\":\"62.50\"}'
like concat('%',`OptionID`,'%')
Condensed Fiddle Example - this demonstrates both approaches

Full JOIN MySQL Query is returning empty

So here is a MySQL Query:
SELECT TestSite . * , LoggedCarts . *
FROM TestSite, LoggedCarts
WHERE TestSite.email = 'LoggedCarts.Bill-Email'
LIMIT 0 , 30
It is returning an empty result set, when it should be returning four results based on the tables below.
First Table: LoggedCarts - Column: Bill-Email
casedilla#hotmail.com
crazyandy#theholeintheground.com
Second Table: TestSite - Column: email
samuel#lipsum.com
taco#flavoredkisses.com
honeybadger#dontcare.com
casedilla#hotmail.com
messingwith#sasquatch.com
The goal is to get a MySQL statement that returns the rows in Table: TestSite that don't match the rows in Table: LoggedCarts.
Note: I understand that the use of a hyphen in a column name requires special care when constructing a query, involving backticks to tell MySQL there are special characters. I would change the column names to match up, however the Table: LoggedCarts has data fed via post from a Yahoo Shopping Cart and without heavy preparation before insertion setting the name to anything but the key sent in the post data is daunting.
However, if it turns out rebuilding the data prior to insertion is easier than using a JOIN statement or for some reason using two columns with different names as the comparison columns just doesn't work, I will go through and rebuild the database and PHP code.
Single quotes indicate a string literal. You need to use backticks for identifiers. Also, each component of an identifier must be quoted individually.
SELECT TestSite . * , LoggedCarts . *
FROM TestSite, LoggedCarts
WHERE TestSite.email = LoggedCarts.`Bill-Email`
LIMIT 0 , 30
From the manual:
If any components of a multiple-part name require quoting, quote them individually rather than quoting the name as a whole. For example, write `my-table`.`my-column`, not `my-table.my-column`.
With a bit of research inspired by somne of the hints given, I found the solution I was looking for here: SELECT * WHERE NOT EXISTS
Does exactly what I need it to do, and as a bonus, I like the shorthand syntax that is used that allows you to put in an alias for the table name and use the alias throughout the statement.
SELECT *
FROM TestSite e
WHERE NOT EXISTS
(
SELECT null
FROM LoggedCarts d
WHERE d.`Bill-Email` = e.email
)

Simple select query not working?

PROVINCE -- varchar(25)
SELECT * FROM listings WHERE PROVINCE='Bakersfield'
Returns empty resultset when entries with Bakersfield as province exist
I am pretty unsure as to why. When I remove the WHERE it works.
BTW I am running this in phpmyadmin, where it lets one execute SQL statements
In phpmyadmin it shows ... beneath the equals sign. I am not sure why. That may be a hint.
If
SELECT * FROM listings WHERE PROVINCE like '%Bakersfield%'
works for you then you have spaces in your data. You can remove them with
update listings
set PROVINCE = trim(PROVINCE)
See TRIM()
After that you should check your code where you insert the data. Check why there are spaces inserted and fix it.
Change you equal = to LIKE operator
SELECT * FROM listings WHERE PROVINCE LIKE 'Bakersfield'
This should solve your issue. If you want to find places that includes your string simply surround it with wildcards %..%
SELECT * FROM listings WHERE PROVINCE LIKE '%Bakersfield%'
SELECT * FROM listings WHERE PROVINCE='Bakersfield'
There is no point the abpve query doesnt work if the follwing case is not the problem.
1) If case is the prob then use upper or lower
SELECT * FROM listings WHERE upper(PROVINCE)=upper('Bakersfield');
2) If extra space is the problem use replace or Trim
SELECT * FROM listings WHERE replace(PROVINCE,' ','') ='Bakersfield'
There might be sum other seniario if not then use "Like " key word as suggested by others. :)

Finding MySQL fields ending in spaces

After a database import, there's some rows with dirty fields that end in (sometimes multiple) spaces saved in the database, and in the interest of finding them amidst the many thousands of other rows, I'm trying to do a query like:
SELECT * FROM `mytable` WHERE `dirtyfield` REGEXP ' $'
But that returns zero rows. I tried a few other variations with other results:
SELECT * FROM `mytable` WHERE `dirtyfield` REGEXP '[[:space:]]$' -- Zero Rows
SELECT * FROM `mytable` WHERE `dirtyfield` REGEXP '[[.space.]]$' -- Zero Rows
SELECT * FROM `mytable` WHERE `dirtyfield` REGEXP '[[.space.]]' -- Those with a space anywhere in the value
SELECT * FROM `mytable` WHERE `dirtyfield` REGEXP '[[.space.]]{2}' -- Those with two spaces in a row
Finding all with a single space doesn't help much, since some clean rows have single spaces between words in that field. That last one catches 90% of the dirty rows, but misses those that have just a single space at the end. Is there something wrong with how I'm using the $ symbol to indicate the end of a field?
The MySQL RIGHT() and SUBSTRING() functions seem to strip off whitespace when calculating the end of the field:
SELECT * FROM `mytable` WHERE RIGHT(`dirtyfield`)=" " -- Only returns one row that has " " for that field
SELECT * FROM `mytable` WHERE SUBSTR(`dirtyfield`,-1)=" " -- Only returns one row that has " " for that field
One other try using a comparison didn't work either:
SELECT * FROM `mytable` WHERE TRIM(`dirtyfield`)!=`dirtyfield` -- zero rows returned
The "dirtyfield" field is a VARCHAR(128), if that matters.
EDIT: I'm an idiot; the fields don't end in spaces, then end in multiple spaces followed by a comma (imported from a bad CSV file).
SELECT * FROM `mytable` WHERE RIGHT(`dirtyfield`,1)=','
That query found them. I was looking at the output of the tables in a comma-separated view and didn't notice the commas were doubled-up.
Had a similar problem. The compare you made with trim():
SELECT * FROM `mytable` WHERE TRIM(`dirtyfield`)!=`dirtyfield`
doesnt work, but:
SELECT * FROM mytable where char_length(dirtyfield) > char_length(trim(dirtyfield))
gets the work done and shows you the rows that have spaces both at the start and/or end of the content. The character count works. Quite honestly i don't know why trim() doesn't compare directly on the first query.
Hope this helps. Like your field, this solution is admittedly a bit dirty.
I think this may be correct:
SELECT * FROM `mytable` WHERE `dirtyfield` REGEXP '[[.space.]]+$'
It matches field ending ($) with 1 or more (+) spaces ([[.space.]])
Anyway if you want to do the same thing with LIKE statement is easier with:
... LIKE '% '
as in answer below.
I have not tried this but I think this might work to find entries that ends with a blank space
SELECT * FROM `mytable` WHERE `dirtyfield` LIKE "% "
Hey i was doing something similar and got in this page, Check below query, this might help..
SELECT * FROM `mytable` WHERE `dirtyfield` LIKE "% %"
Have you considered that you actually get rows with spaces in it, but the web browser doesn't render them for you?
The value " two (2 or more spaces) words " looks like "two words" in your browser.
Try a:
WHERE dirtyfield REGEXP '(^[[:space:]]|[[:space:]]{2,}|[[:space:]]$)'
This should fetch all of those rows. Just consider that you might get the right rows, but it doesn't look that way due to browser.