开发者

MySQL select query, selecting where from a column generated on-the-fly

开发者 https://www.devze.com 2023-01-25 22:11 出处:网络
I have a (my)SQL question. If I have a table, let\'s say called Cars with various columns, two of which are INT which I want to add together, one called backwheels and the other called front开发者_运维

I have a (my)SQL question. If I have a table, let's say called Cars with various columns, two of which are INT which I want to add together, one called backwheels and the other called front开发者_运维问答wheels.

I can do this query to add them together when I select

select (backwheels+frontwheels) as totalwheels from Cars;

which works fine, but when I try and do a select where on that totalwheels column, I get an error

select (backwheels+frontwheels) as totalwheels from Cars where totalwheels=4;

the error I get back:

Unknown column 'totalwheels' in 'where clause'

Is it possible to somehow select from a column which doesn't really exist like this?


You can use:

select (backwheels+frontwheels) as totalwheels from Cars
where (backwheels+frontwheels)=4;

OR:

SELECT * from 
(select c.*, (backwheels+frontwheels) as totalwheels from Cars)
where totalwheels=4;


This error is caused because your table doesn't have a column "totalwheels" and your where clause is trying to run a condition on a column that doesn't exist.

You can try using -

select (backwheels+frontwheels) as totalwheels from Cars where (backwheels+frontwheels)=4;


Better try with Alias:

select (c.backwheels+c.frontwheels) as totalwheels from Cars as c where totalwheels=4;
0

精彩评论

暂无评论...
验证码 换一张
取 消