Join syntax on MYSQL - mysql

For MYSQL syntax I understand the Joins are FROM table JOIN table ON table.column = table.column I have come across other forms of joins that seam to not only not follow that syntax but the two columns do not relate rather they compliment each-other example below
from coordinates as cod join
geofences as geo
on st_contains(geo.simplified_shape, cod.request_point)
For context this is saying st_contains where A contains B so essentially is this satisfying the join if indeed the request point is in the geo fence shape? I know this is a valid syntax this question is more on if someone can illuminate not only the joins within a parentheses and when that can be applicable rather than the = sign is it only in these specific instances and if my line of thinking is correct that the tables can join not because the values are equivalent but because it satisfies the st_contains condition so for example if you used something else other then st_contains how would that look?

This is really equivalent to:
on st_contains(geo.simplified_shape, cod.request_point) <> 0
What is happening here is that MySQL is converting the result to a "boolean". If the function returns a number, then any non-zero number is "true" and zero is "false".
If the returned value is a string, then the string is converted to a number, based on the leading digits. If there are no leading digits, the value is zero. Then this is treated as a boolean.

Related

Why does a query return a result if the field is numeric and the WHERE clause is a string?

I am running a query on a db table which is returning one record when I expect it to return no records.
SELECT yeargroupID FROM tbl_yeargroup WHERE yeargroup='S' AND schoolID=2.
The yeargroup field is a tinyint field. Thefore the WHERE clause is looking the letter 'S' in the numeric field, so should not find anything. Yet it returns the record with the yeargroup = 0, and yeargroupID=17 (the bottom record in the table)
I'm confused as to why it is returning this record and how to avoid it.
Thanks
This logic, as you have pointed out, is comparing a number and a string:
WHERE yeargroup = 'S'
Handling such situations is an important part of most SQL compilers, and it is well documented. The solution is to implicitly convert values to "conforming" types. This is sad. My preference would be for the compiler to generate an error and force the user to use correct types. I find that implicit conversion creates more problems than it solves.
In any case, the rules in this case are pretty simple. The string is converted to an integer. But, how is a string with no digits converted? Well, the rule in MySQL is that the leading digits are converted to a number. And if there are none, the value is 0. So, this turns into:
where yeargroup = 0
You can see the results more clearly if you run:
select 'S', 'S' + 0
Note that most databases would return an error in this case (a type conversion error). But even those would accept the string if it looked like a number, so this would be allowed:
where yeargroup = '5'
What is the proper solution? Never mix types. Do not construct queries by munging constant values. Instead, queries from an application should always be using parameters.

Why does MySQL equal sign matches wrong entries?

I'm running a select query on two tables and searching the matching entries with an equal sign. In my understanding, MySQL should only return entries exactly matching the WHERE condition, however it's returns entries like when I use the LIKE statement:
Any explanations why would the first row be returned as a result of the query?
EDIT:
Here's the query:
SELECT `ts`.`ticker_symbol`, `sm`.`id` AS `matchescount`, `sm`.`ticker_symbol_ids`
FROM `mk_ticker_symbols` `ts`, `mk_submissions` `sm`
WHERE `sm`.`ticker_symbol_ids` = `ts`.`id` AND `ts`.`id` = "1506"
EDIT 2:
Here's the SQL Fiddle:
http://sqlfiddle.com/#!9/5550b/1/0
EDIT 3:
Here's the SQL Fiddle with JOINs:
http://sqlfiddle.com/#!9/5550b/2/0
Piero,
The one with JOINs can be corrected. CAST() within JOIN will fix the issue.
INNER JOIN `mk_submissions` `sm`
ON `sm`.`ticker_symbol_ids` = CAST(`ts`.`id` AS CHAR(10))
I know you are not looking for solution, but I still post it.
The problem is VERY interesting.
I searched online, and did some trial-error on my DB. I have no explanations....
I tried to put 1506, in the second, or third place in comma separated list - the query works fine.
So, I have a feeling, that in case of JOIN with comma-separated list, comma gets treated as wildcard 'end of string'...
If you ever find an explanation, please post it here.
When evaluating expressions, MySQL converts both arguments (in this case) to floating point numbers to compare them. This is because one is a string, and one is an integer, which results in the final condition in the link above being applied.
In all other cases, the arguments are compared as floating-point
(real) numbers.
So what is the floating point equivalent of the string "1506,..."?
Running the following on my test server:
SELECT "1506,3101,26673,26745,2277,1216,26847,26865,20711,1468,26947,233,20539,26985"+0.0
Results in:
1506
Which of course equals the floating point version of the integer 1506.
So, everything is behaving as expected. At least, assuming you expect this floating point comparison to be happening.
I can't give a full explanation for the problem, but I have a solution.
ts.id is likely and INTEGER so your where clause should be
`ts`.`id` = 1506
(remove quotes from the number).
Also you should use a join instead of a where clause to match the tables:
FROM `mk_ticker_symbols` `ts`
JOIN `mk_submissions` `sm` on sm.ticker_symbol_ids = ts.id
I found the answer to this issue. I was comparing string to integer here:
`sm`.`ticker_symbol_ids` = `ts`.`id` AND `ts`.`id` = "1506"
The problem is that, this is converted to integer internally for comparison:
1506,3101,26673,26745,2277,1216,26847,26865,20711,1468,26947,233,20539,26985
Because of the comma, MySQL thinks it's a decimal or float with the floating point, and everything after the comma is omitted for comparison. So it becomes 1506 instead of 1506,3101,26673,26745,2277,1216,26847,26865,20711,1468,26947,233,20539,26985, and that matches the WHERE condition.
#cyadvert and #Willem_Renzema were absolutely correct.
To resolve the issue
I only needed to:
CAST(`ts`.`id` AS CHAR)

how do I inner-join an integer substring of a URL to an integer?

I have two MySQL tables in Joomla: categories and Menu.
The field menu.link has values like index.php?option=com_content&view=category&id=175.
The number after the very last equal sign is equal to the field categories.id.
I would like to create INNER JOIN between two tables so that categories.id will be equal to the number in menu.link.
I understand I have to remove all before the number, but how shall I do that?
It seems you are looking for a SQL expression that will extract the id value from your URL string. This is always a dicey proposition because it depends on unpredictable details of the format of the URL.
It's a doubly dicey proposition in MySQL because there aren't any regexp functions that return actual string values. They only return true/false. So you need to use non-regexp string processing functions to extract your data.
That being said, let us hack away. This expression will get that number.
CAST(SUBSTRING_INDEX(menu.link,'view=category&id=',-1) AS INT) AS cat_id
The heart of this string-processing hack is the string 'view=category&id='. The SUBSTRING_INDEX function retrieves everything to the right of that string, and the CAST operation takes just the integer.
If the substring is not found, the expression returns zero. That might or might not be what you want. (I said this was dicey!)
So, to perform the join you'd do something like this:
SELECT Menu.whatever,
categories.whatever
FROM Menu
JOIN categories
ON categories.id = CAST(SUBSTRING_INDEX(menu.link,'view=category&id=',-1) AS INT)
This will perform poorly. But that's probably OK because you won't have tens of thousands of rows in either table.

Is this a valid SQL conditional expression or a MySQL bug (feature)?

Trying to debug some joins which seemed to returning cartesian products I typed the equivalent ON condition into selects.
In MySQL
select *
from table
where columnname
seems to behave as though I typed where columname is not null. In joins typing on table.columnname is accepted but returns LOTS of rows. MySQL does the right thing if I correct it to on table1.column=table2.column but surely my first version was incorrect and illegal.
The contexts you are talking about, the WHERE clause and the ON clause in a join, simply accept an expression.
SELECT ...
FROM table1 JOIN table2 ON <expr>
WHERE <expr>
Expressions can include comparison operators like = but expressions can also be as simple as a single column or a single constant value.
Compare with another context that accepts an expression: the select-list.
SELECT <expr>, <expr>, <expr>
It's normal to use a single column as the expression in this context.
Most programming languages consider all values other than null, 0, '', false as true.
while(1); is an infinite loop irrespective of whether you give 1,2,'a',true and so on. I would say its a default expected behaviour and I have often used similar where clause

Using REGEX to alter field data in a mysql query

I have two databases, both containing phone numbers. I need to find all instances of duplicate phone numbers, but the formats of database 1 vary wildly from the format of database 2.
I'd like to strip out all non-digit characters and just compare the two 10-digit strings to determine if it's a duplicate, something like:
SELECT b.phone as barPhone, sp.phone as SPPhone FROM bars b JOIN single_platform_bars sp ON sp.phone.REGEX = b.phone.REGEX
Is such a thing even possible in a mysql query? If so, how do I go about accomplishing this?
EDIT: Looks like it is, in fact, a thing you can do! Hooray! The following query returned exactly what I needed:
SELECT b.phone, b.id, sp.phone, sp.id
FROM bars b JOIN single_platform_bars sp ON REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(b.phone,' ',''),'-',''),'(',''),')',''),'.','') = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(sp.phone,' ',''),'-',''),'(',''),')',''),'.','')
MySQL doesn't support returning the "match" of a regular expression. The MySQL REGEXP function returns a 1 or 0, depending on whether an expression matched a regular expression test or not.
You can use the REPLACE function to replace a specific character, and you can nest those. But it would be unwieldy for all "non-digit" characters. If you want to remove spaces, dashes, open and close parens e.g.
REPLACE(REPLACE(REPLACE(REPLACE(sp.phone,' ',''),'-',''),'(',''),')','')
One approach is to create user defined function to return just the digits from a string. But if you don't want to create a user defined function...
This can be done in native MySQL. This approach is a bit unwieldy, but it is workable for strings of "reasonable" length.
SELECT CONCAT(IF(SUBSTR(sp.phone,1,1) REGEXP '^[0-9]$',SUBSTR(sp.phone,1,1),'')
,IF(SUBSTR(sp.phone,2,1) REGEXP '^[0-9]$',SUBSTR(sp.phone,2,1),'')
,IF(SUBSTR(sp.phone,3,1) REGEXP '^[0-9]$',SUBSTR(sp.phone,3,1),'')
,IF(SUBSTR(sp.phone,4,1) REGEXP '^[0-9]$',SUBSTR(sp.phone,4,1),'')
,IF(SUBSTR(sp.phone,5,1) REGEXP '^[0-9]$',SUBSTR(sp.phone,5,1),'')
) AS phone_digits
FROM sp
To unpack that a bit... we extract a single character from the first position in the string, check if it's a digit, if it is a digit, we return the character, otherwise we return an empty string. We repeat this for the second, third, etc. characters in the string. We concatenate all of the returned characters and empty strings back into a single string.
Obviously, the expression above is checking only the first five characters of the string, you would need to extend this, basically adding a line for each position you want to check...
And unwieldy expressions like this can be included in a predicate (in a WHERE clause). (I've just shown it in the SELECT list for convenience.)
MySQL doesn't support such string operations natively. You will either need to use a UDF like this, or else create a stored function that iterates over a string parameter concatenating to its return value every digit that it encounters.