MySQL error 1064: SQL syntax error in SELECT statement - php

I am relatively new to somewhat advanced MySQL querying. I had been trying to query the most recent order in an order table of a particular user using MySQL SELECT statement using the following MySQL query.
SELECT o1.* FROM order AS o1
WHERE o1.orderDateTime =
(
SELECT MAX(o2.orderDateTime) FROM order AS o2
WHERE o2.userId = '1'
)
But I had been constantly getting the following MySQL error #1064 related to MySQL syntax.
#1064 - 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 'order AS o1 WHERE o1.orderDateTime = (SELECT MAX(o2.orderDateTime)FROM order AS ' at line 1
I got similar errors in relation with INSERT statements but I managed to fix it up using the methods specified in MySQL 1064: You have an error in your SQL syntax
I made every effort to fix the query in the current case but I was still unsuccessful.
I would be grateful to you if someone can help me out with fixing this MySQL syntax error for SELECT clause specified above. It would be great if someone could specify me the exact reason for the occurrence of this issue, as well.

order is a reserved word and its a bad choice for table name. You need to escape using backticks in the query
SELECT o1.* FROM `order` AS o1
WHERE o1.orderDateTime = (
SELECT MAX(o2.orderDateTime) FROM `order` AS o2
WHERE o2.userId = '1'
)
http://dev.mysql.com/doc/mysqld-version-reference/en/mysqld-version-reference-reservedwords-5-5.html

As per #Abhik, order is a MySQL keyword.
And you should avoid collapse with two methods:
Use backticks (`) (#Abhik has already explained this.)
Prepend Database name before Table Name e.g.
DataBase_Name.order.
But, still #Abhik's approach is preferable as in case of database name change, you need to change DataBase name in your query.

First of all you could follow #Abhik Chakraborty suggestion to include back ticks around order table name. order is a reserved word in mysql. My suggestion was to improve your sql query. YOu could acomplish the same using:
SELECT o1.* FROM `order` o1
WHERE o1.userId = '1' order by orderDateTime desc limit 1
the subquery seems unnecessary.

Related

What is the best way to do the job of Group By in mysql when sql_mode=only_full_group_by

I want to perform a query like to get the last record of any type in DB, at my localhost, I use Maria Db and the query is as follow:
SELECT *
FROM table_a
WHERE column_a=999
OR column_b=999
GROUP
BY `group`;
group is a column which I save type in it, for instance: marketing, blog, order, etc
This query works fine on local, but on the server I get the following error:
SQLSTATE[42000]:
Syntax error or access violation:
1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column
'db_name.table_a.id' which is not functionally dependent on columns in GROUP BY clause;
this is incompatible with sql_mode=only_full_group_by\n
The SQL being executed was:
SELECT * FROM `table_a` WHERE (`column_a`=999) OR (`column_b`=999) GROUP BY `group`"
According to MySQL document I can use the following command to make this possible:
SET GLOBAL sql_mode=(SELECT REPLACE(##sql_mode,'ONLY_FULL_GROUP_BY',''));
But I don't have the sufficient privilege on Db and get the following error:
#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation
I asked the hosting to do this for me, they replied that they don't want to do this action
I use the YII2 framework, and now I want a way to add this on the option of database_config.php of the framework or change the query to something else with the same result, and not losing performance
ONLY_FULL_GROUP_BY is a good thing, which enforces basic ANSI SQL rules. Don't change it, fix your code instead.
From there one: you want entire records, so you should not think aggregation, but filtering.
Then: in a database table, records are unordered; for your question to just make sense, you need a column that defines the ordering of rows in each group, so it unambiguous what "last" record mean. Let me assume that you have such column, called id.
Here is a typical approach at this top-1-per-group problem, using a correlated subquery for filtering:
SELECT *
FROM table_a a
WHERE
999 IN (column_a, column_b)
AND id = (
SELECT MAX(a1.id)
FROM table_a a1
WHERE 999 IN (a1.column_a, a1.column_b) AND a1.grp = a.grp
)
Alternatively, if you are running MySQL 8.0, you can use window functions:
SELECT *
FROM (
SELECT a.*,
ROW_NUMBER() OVER(PARTITION BY grp ORDER BY id DESC) rn
FROM table_a a
WHERE 999 IN (column_a, column_b)
) a
WHERE rn = 1
Side note: group is a language keyword, hence a poor choice for a column name. I renamed it to grp in the queries.
There are a few ways to "bypass" the sql_mode but be aware that the result you get might not be correct.
First you can use ANY_VALUE(). Example like this:
SELECT any_value(column_a), any_value(column_b), `group` FROM table_a
WHERE (column_a=999) OR (column_b=999) GROUP BY `group`;
When using ANY_VALUE() function you have to write all the columns in SELECT from the table and append with ANY_VALUE() except for the column that you use in the GROUP BY.
Using MAX() or MIN() can return result but still it might not be the correct
result, especially for any row(s) that have more than 1 count:
SELECT MAX(column_a), MAX(column_b), `group`
FROM table_a
WHERE (column_a=999) OR (column_b=999) GROUP BY `group`;
Using GROUP_CONCAT will give you a view at what are the values in non-grouped columns. Compare the results with the other queries above and you can see on row(s) that returns more than one count, does the other queries returning according to what you want?
SELECT group_concat(column_a), group_concat(column_b), group_concat(`group`)
FROM table_a
WHERE (column_a=999) OR (column_b=999) GROUP BY `group`;
I'm not sure if you can do this but you can set the sql_mode off temporarily then you should be able to run your query:
SET sql_mode=""; -- you don't need to set global privilege.
SELECT * FROM table_a
WHERE (column_a=999) OR (column_b=999) GROUP BY `group`;
Demo here.
Still, the best option is to retain the sql_mode as it is and construct the query according to the requirement.
P/S: GROUP is a reserved word in both MySQL & MariaDB. You can use it as column name but you have to always add back-ticks to define the column or else, running the query will return you an error like
Query: select * from table_a group by group
Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'group' at line 1

unable to use full text search with mysql query using MATCH and AGAINST

hope someone can help me. I am trying to use the full search text MATCH and AGAINST.
I am getting this error
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''mytable' WHERE MATCH(user) AGAINST('alex') LIMIT 0, 25' at line 1
my example query is:
SELECT id, user FROM 'mytable' WHERE MATCH(user) AGAINST('alex') LIMIT 0, 25
You can only use backticks around table or column name, you can not use anything except backticks.
SELECT id, user FROM `mytable` WHERE MATCH(user) AGAINST('alex') LIMIT 0, 25
Where backticks required?
If your table or column name contains any MYSQL reserve word than you must need to use backtick around the name.
MYSQL Reserve Keywords and Words
You don't need to quote mytable. DOCS
SELECT id, user FROM mytable WHERE MATCH(user) AGAINST('alex') LIMIT 0, 25
For the error mentioned.
ALTER TABLE mytable ADD FULLTEXT index_name(user);
The fulltext index should contain exactly the same number of columns, in same order as mentioned in MATCH clause.
Here for more.

Use of CONCAT in FROM clause

I have a non-working query as the sub-query FROM clause doesn't understand CONCAT():
SELECT *
FROM `events` e
WHERE EXISTS (SELECT *
FROM CONCAT('prefix_', e.`event_id`) registrations
WHERE registrations.`attendee` = 123456
)
Is there any way to make this work in a single-statement?
The error message I receive is:
#1064 - 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 '('prefix_', e.event_id) registrations
You are trying to dynamically come up with a table name? I don't think this is possible...because doesn't the FROM clause table name need to be resolved prior to the SQL being able to be evaluated and executed?
SELECT * FROM (SELECT *,
CONCAT('prefix_', `event_id`) as prefix FROM `events`
WHERE events.attendee = 123456
);

SQL/PHP query error

I have the following error:
1064 - 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 'select manufacturers_id, manufacturers_name, manufacturers_image, date_added, la' at line 1
The query:
SELECT COUNT(
SELECT manufacturers_id,
manufacturers_name,
manufacturers_image,
date_added,
last_modified
FROM manufacturers
ORDER BY manufacturers_name
) AS total
This happens also to some other categories in my website. All finish their line incomplete.
This query would do what you want:
SELECT COUNT(*) AS total
FROM manufacturers
What's wrong with your query:
COUNT() accepts an expression or single column as parameter - you're passing multiple
ORDER BY doesn't make much sense as soon as what you need is just number of rows (for obvious reason that number doesn't depend on order)
Maybe because the code is not on here full but what I can see is the mysql/mysqli_query is missing, and the ";" at the end of the code.

How do I handle single quotes inside a SQL query in PHP?

I am using a particular query for inserting records. It is going well. I am even fetching records with a select query. But my problem is that, if the record contains single quotes ' ', then it gives me this error:
> NOTE: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 'B''' at line 1
The SELECT query is:
$result= mysql_query("SELECT s.name,
s.sid as sid,
s.category,
p.name as pname
FROM poet p
INNER JOIN song s
ON p.pid = s.pid
WHERE s.name= '$sid'") or die(mysql_error());
What should I do to skip quotes problem in this. When I want quotes to insert in my records.
Your problem is much worse than this -- what if someone enters the value '; DROP TABLE poet; --? You need to use either mysql_real_escape_string() to escape the value, or use parametrized queries (with PDO, for example).
It's 2011, for crying out loud. Why is SQL injection still a widespread problem?
You have to escape the data
$sid = mysql_real_escape_string($sid);
use http://www.php.net/manual/en/function.mysql-real-escape-string.php function on your string to quote "'" and other special symbols
Other way to prevent injection - use different connections (login-passwords) with different rights for inserting and selecting. In this case mysql_real_escape_string wi9ll work good

Categories