Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DELETE FROM `table` AS `alias` ... WHERE `alias`.`column` ... why syntax error?

I tried this with MySQL:

DELETE FROM `contact_hostcommands_relation` AS `ContactHostCommand` WHERE (`ContactHostCommand`.`chr_id` = 999999) LIMIT 1 

And I get this:

#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 'WHERE (`ContactHostCommand`.`chr_id` = 999999) LIMIT 1' at line 1 

Note: This query is automatically generated and conditions are based on table aliases.

Why I get this error?

Is there any way to use table aliases in where clause?

Is this MySQL specific?

like image 392
Aalex Gabi Avatar asked May 07 '12 15:05

Aalex Gabi


People also ask

Can we use alias in delete query?

Recently I wrote about the myth that you can't use an alias in an UPDATE statement. You can of course, and the trick is to make sure that the alias is used in the FROM clause of the statement.

Can we use column alias in WHERE clause?

Column Alias Column aliases can be used for derived columns. Column aliases can be used with GROUP BY and ORDER BY clauses. We cannot use a column alias with WHERE and HAVING clauses.

How do I specify a column alias?

The basic syntax of a table alias is as follows. SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition]; The basic syntax of a column alias is as follows.

What is table alias What is the purpose of table alias?

A table alias is also called a correlation name. A programmer can use an alias to temporarily assign another name to a table or column for the duration of a SELECT query. Assigning an alias does not actually rename the column or table.


2 Answers

What @Matus and @CeesTimmerman said about MSSQL, works in MySQL 5.1.73 too:

delete <alias> from <table> <alias> where <alias>.<field>... 
like image 187
Rafael Barros Avatar answered Oct 06 '22 15:10

Rafael Barros


You can use SQL like this:

DELETE FROM ContactHostCommand  USING `contact_hostcommands_relation` AS ContactHostCommand  WHERE (ContactHostCommand.`chr_id` = 999999)  LIMIT 1 
like image 27
Sarunas Avatar answered Oct 06 '22 13:10

Sarunas