Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL AS in WHERE statement

Tags:

mysql

I have a MySQL database. I use a SELECT AS to measure "distance" between 2 points. What I want to do is use the same "distance" variable I created in the SELECT as a WHERE condition.

SELECT first_name.last_name AS name WHERE name="John Doe"

What is the best way to accomplish this?

like image 382
ATLChris Avatar asked Jan 06 '11 03:01

ATLChris


People also ask

Which is the AS clause used for?

The AS clause allows you to give an alias name to EQL attributes and results. The alias name can be given to an attribute, attribute list, expression result, or query result set. The aliased name is temporary, as it does not persist across different EQL queries.

Can I use alias in WHERE SQL?

The WHERE clause can contain non-correlated aliases and correlated aliases.

What is %s and %D in MySQL?

12 years, 11 months ago. it's for php to know how to handle the parameters, %d – the argument is treated as an integer, and presented as a (signed) decimal number. %s – the argument is treated as and presented as a string. in your examples, $slug is a string and $this->id is an integer.

What is the AS statement in SQL?

The AS command is used to rename a column or table with an alias. An alias only exists for the duration of the query.


2 Answers

You may want to consider putting your condition in a HAVING clause rather than in the WHERE clause.

See http://dev.mysql.com/doc/refman/5.5/en/select.html for details on the HAVING clause.

like image 82
asm Avatar answered Oct 30 '22 06:10

asm


Column aliases can only be referenced in the ORDER BY clause (as they do not exist yet in the WHERE part. You can do this (Although I do not necessarily recommend it as it may be slower.)

select name from
(select concat(firstname, ' ', lastname) as name from yourtable)
where name = 'John Doe'

Or you could do this:

select (firstname, ' ', lastname) as name from yourtable
where (firstname, ' ', lastname) = 'John Doe';

The only columns you have access to in the WHERE clause are the columns in the FROM clause.

like image 30
nate c Avatar answered Oct 30 '22 06:10

nate c