MySQL Syntax Error on complicated query - mysql

Sorry for the derp question (as I'm sure it probably is), but after going over the manual and through Stack Overflow for answer on this one, I'm still unsure of what's wrong with this database query.
Some info:
I'm trying to create a function that creates an array of all zipcodes within a radius around another zipcode. I'm using this as reference: http://www.movable-type.co.uk/scripts/latlong-db.html
I have actually had this string working on my live site, however I'm now redoing some work on my localhost (WAMP) which is running MySQL 5.5.24. The platform is Wordpress.
I understand that quotes (or a lack thereof) around database names, fields, etc and I've used several variations with no luck at all.
Anyways, enough talk. Here's the error:
[You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''geo_data' WHERE 'Lat>44.566' AND 'Lat<44.566' AND 'Lon>-109.208' AND 'L' at line 4]
And here's the code:
SELECT 'Postcode', 'Lat', 'Lon', 'acos(sin($lat)*sin(radians(Lat)) + cos($lat)*cos(radians(Lat))*cos(radians(Lon)-$lon))*$R' AS D
FROM (
SELECT 'Postcode', 'Lat', 'Lon'
FROM 'geo_data'
WHERE 'Lat>$minLat' AND 'Lat<$maxLat'
AND 'Lon>$minLon' AND 'Lon<$maxLon'
)
AS 'firstcut'
WHERE 'acos(sin($lat)*sin(radians(Lat)) + cos($lat)*cos(radians(Lat))*cos(radians(Lon)-$lon))*$R' < '$rad'
ORDER BY 'D'
Thanks for the help, sorry again if I'm missing the obvious.
EDIT
Thanks guys! Got it working. Here's the working code for the benefit of others:
SELECT `Postcode`, `Lat`, `Lon`, acos(sin($lat)*sin(radians(`Lat`)) + cos($lat)*cos(radians(`Lat`))*cos(radians(`Lon`)-$lon))*$R AS `D`
FROM (
SELECT `Postcode`, `Lat`, `Lon`
FROM `geo_data`
WHERE `Lat`>'$minLat' AND `Lat`<'$maxLat'
AND `Lon`>'$minLon' AND `Lon`<'$maxLon'
)
AS `firstcut`
WHERE acos(sin($lat)*sin(radians(`Lat`)) + cos($lat)*cos(radians(`Lat`))*cos(radians(`Lon`)-$lon))*$R < '$rad'
ORDER BY `D`

You're using single quotes ' around your field and table names. This is incorrect. You want to use backticks `. Using quotes makes MySQL interpret it as a string.
You also have your conditions and calculations inside quotes, that just makes them into strings.
For example, your inner query should look like this:
SELECT `Postcode`, `Lat`, `Lon`
FROM `geo_data`
WHERE `Lat > '$minLat' AND `Lat` < '$maxLat'
AND `Lon`> '$minLon' AND `Lon` < '$maxLon'

'geo_data' is a string geo_data [with backticks (`)] is a tablename

Related

MySQL: Comparing the result of two convert functions

Im currently working on a database that have been initialize with dates in varchar instead of using datetime format.
I'm supposed to compare the dates of the DB with an input date (31/05/2020 actually).
Here is the part of my code that makes troubles :
AND Convert(datetime,t1.fin_contrat, 103) > Convert(datetime, '31/05/2020', 103 )
But I've an error from PhpMyAdmin which is : #1064 - Syntax error near 't1.fin_contrat, 103) >= Convert(datetime, '31/05/2020', 103 ) GROUP BY siren OR' line 1
According to this link : https://learn.microsoft.com/fr-fr/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15#implicit-conversions varchar should be able to being converted directly to datetime value.
I tried to use WHERE instead of AND it doesn't work. So I'm out of option, and i'm seeking for ideas.
Thanks for your help
In MySQL, you want something like this:
where date(t1.fin_contrat) = str_to_date('31/05/2020', '%d/%m/%Y')
This corresponds to the code in your question, but adapted for MySQL.
The fonction CONVERT is not the same betweeen Microsoft SQL. and Mysql
https://dev.mysql.com/doc/refman/5.7/en/cast-functions.html#function_convert
To convert a string. to a date. you must use STR_TO_DATE
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_str-to-date
ps:
Every sql server software ( Oracle , Redshift , Posgtres , Mysql , MariaDB , MS SQL server , Sqllite , ...) has his own SQL dialect . Usually simple queries are portable but more complex or using functions queries must be rewriten .

error code 1064: syntax error in SQL query

Can anyone tell me what is wrong with below python query?SU_version is of datatype varchar(45) ,let me know if any details are required.
SELECT gerrit_id
FROM gerrit_table
where (SU_version>=00.00.0086
and SUversion<=00.00.0085
and PL=LA.BF64.1.1
and component=SU_CNSS_BT_FM_Redfox64);
Presumably the problem are the constants. These look like strings, so they should be surrounded by single quotes:
SELECT gerrit_id
FROM gerrit_table
WHERE SU_version >= '00.00.0086' and SUversion <= '00.00.0085' and
PL = 'LA.BF64.1.1' and component = 'SU_CNSS_BT_FM_Redfox64';
You said that SU_version is varchar, so why are you using >= in where clause, maybe try to cast it before using >= and also in your pl, you should enclose it in quotes try this code
SELECT gerrit_id
FROM gerrit_table
where (cast(SU_version as double)>=00.0086
and SUversion<=00.00.0085
and PL='LA.BF64.1.1'
and component='SU_CNSS_BT_FM_Redfox64');
I don't know what is LA.BF64.1.1 and SU_CNSS_BT_FM_Redfox64, so i assume they're just user input, hope this will help

MySQL Syntax error for 5.6.17_1

I have MySQL 5.6.17_1 and have query that is used for 5.1.xx
select
schtermid,idfptnsubid,d.idfptnid,idflinksetid,
cast(count(distinct cthr) as real)/cast(count(distinct s.schid) as real)*100 as ctr, cast(sum(status) as real)/cast(count(*) as real)*100 as pfiled,
count(distinct s.schid) as schcount
from source.kdm_session as
This complains
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
'real)/cast(count(distinct s.schid) as real)*100 as ctr, cast(sum(status) as' at line 3
Which part is wrong? What should I change to get the same thing to happen?
As per the docs, real is not a valid type:
The type for the result can be one of the following values:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
Try this for your calcs:
(count(distinct cthr) * 1.0)/(count(distinct s.schid) * 1.0)*100 as ctr,
(sum(status) * 1.0)/(count(*) * 1.0)*100 as pfiled,
This is rather a mess - you are mixing up the arguments and inventing types. You're also trying to use AS both as a seperator within a call to CAST() and as an alias operator. Since its meaning is contextual it's good practice not to mix and match in the same query.
Formatting part of your query...
cast(
count(distinct cthr) as real)
/ cast(
count(distinct s.schid) as real
)*100 as ctr
, cast(sum(status) as real)
/cast(count(*) as real)*100 as pfiled
Sorry - but this is so messed up I haven't a clue what you are trying to do here. You seem to be trying the cast the result of a calulation to a type defined by the result of another calculation. Since the can't all have the same alias I guess you must think that 'real' is a type in MySQL (it isn't). Even if you meant a floatling point number - this is just silly - the result of a count is always an integer. You don't even have the same number of opening and closing brackets.
In addition to NOT using 'AS' within CAST(), and using the valid MySQL types, if you formatted your quesry better and provided examples of inputs and outputs we might have a chance at helping you.

Rails 3 MySQL 2 reports an error in what looks to be valid SQL syntax

I am trying to use the following bit of code to help in seeding my database. I need to add data continually over development and do not want to have to completely reseed data every time I add something new to the seeds.rb file. So I added the following function to insert the data if it doesn't already exist.
def AddSetting(group, name, value, desc)
Admin::Setting.create({group: group, name: name, value: value, description: desc}) unless Admin::Setting.find_by_sql("SELECT * FROM admin_settings WHERE group = '#{group}' AND name = '#{name}';").exists?
end
AddSetting('google', 'analytics_id', '', 'The ID of your Google Analytics account.')
AddSetting('general', 'page_title', '', '')
AddSetting('general', 'tag_line', '', '')
This function is included in the db/seeds.rb file. Is this the right way to do this?
However I am getting the following error when I try to run it through rake.
rake aborted!
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group = 'google' AND name = 'analytics_id'' at line 1: SELECT * FROM admin_settings WHERE group = 'google' AND name = 'analytics_id';
Tasks: TOP => db:seed
(See full trace by running task with --trace)
Process finished with exit code 1
What is confusing me is that I am generating correct SQL as far as I can tell. In fact my code generates the SQL and I pass that to the find_by_sql function for the model, Rails itself can't be changing the SQL, or is it?
SELECT * FROM admin_settings WHERE group = 'google' AND name = 'analytics_id';
I've written a lot of SQL over the years and I've looked through similar questions here. Maybe I've missed something, but I cannot see it.
"group" is a keyword so you can't use it as-is as an identifier, you have to quote it with backticks (for MySQL at least):
SELECT *
FROM admin_settings
WHERE `group` = 'google'
AND name = 'analytics_id'
Any SQL that Rails/ActiveRecord generates will use the quoted version of the column name so I'd guess that you're generating some SQL (or just a snippet of SQL for the WHERE clause) and neglecting to quote the column names.
I'd recommend against using group as a column name, use something else so that you don't have to worry about sprinkling backticks all over the place in your code.
group is an invalid field name if left unquoted, as it is a SQL keyword. To fix, surround it with backticks in your find_by_sql query, so your DB doesn't attempt to interpret it as the GROUP keyword.

Update Else Insert MySQL query

Hello i was here yesterday with this problem, i don't really know how to use this site well as i am new so i reposted. but I'm getting an error with this block of code and i think its the Update query which contains a syntax error.
// Updates if player's record already exists
$result = mysql_query("UPDATE PlayerStat SET Position='$POS', Number='$NUM', Name='$PlyrName', Status='$Status', TDS='$TDS', INT='$INT', YDS='$YDS', RTG='$RTG', Team='$Team' WHERE Name='$PlyrName'");
echo mysql_error();
if (mysql_affected_rows()==0){
// Populates table if record is non existent
$result = mysql_query("INSERT INTO PlayerStat(`Position`, `Number`, `Name`, `Status`, `TDS`, `INT`, `YDS`, `RTG`, `Team`) VALUES ('$POS','$NUM','$PlyrName','$Status','$TDS','$INT','$YDS','$RTG','$Team')");
echo mysql_error();
}
The Error message
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INT='1', YDS='86', RTG='52.5', Team='ARI' WHERE Name='Bartel, Richard'' at line 1
INT is a keyword in mysql (declares and integer), if it's your column name you should surround it backticks (`) like so: `INT`.
It's good practice to put these in even though they're not necessary in all cases
UPDATE
PlayerStat
SET
`Position` = '$POS',
`Number` = '$NUM',
`Name` = '$PlyrName',
`Status` = '$Status',
`TDS` = '$TDS',
`INT` = '$INT',
`YDS` = '$YDS',
`RTG` = '$RTG',
`Team` = '$Team'
WHERE
`Name` = '$PlyrName'
Two things:
Check the manual for INSERT ... ON DUPLICATE KEY UPDATE which should do this in one statement.
I suggest you take a hard look at mysql_real_escape_string() or similar in PHP to escape your data and prevent SQL Injections.
If you don't know what SQL Injections are, then google it and spend a bit of time reading NOW before it's too late and some cracker or script kitty has your database.
Hope this helps!
You may want to check these websites.
http://www.w3schools.com/php/php_mysql_update.asp
http://www.tizag.com/mysqlTutorial/mysqlupdate.php
And you might also want to check your spelling mistake or the single quote or double quote. Other than that, check your database namings and data type.