ayok Posted February 22, 2012 Share Posted February 22, 2012 Hi, I'm trying to select the difference between column 'original_price' and 'price' which is less than certain amount. Here is my query. SELECT *,(original_price - price) AS profit FROM items WHERE profit <= '50.00' ORDER BY RAND() It gives me a mysql error that profit is not exist. Would someone tell me how to get expected result? Thank you. ayok Link to comment https://forums.phpfreaks.com/topic/257578-select-the-difference-between-2-column/ Share on other sites More sharing options...
requinix Posted February 22, 2012 Share Posted February 22, 2012 You can't use aliases in WHERE clauses - pretend that aliasing happens after the conditions. HAVING doesn't have that restriction. SELECT *, (original_price - price) AS profit FROM items HAVING profit While I'm at it, 1. If a number is supposed to be a number, don't put quotes around it. 2. Are you sure you want to ORDER BY RAND()? Do you actually want [i]all[/i] of the results in a random order? Or do you just want a couple of them chosen randomly? Link to comment https://forums.phpfreaks.com/topic/257578-select-the-difference-between-2-column/#findComment-1320241 Share on other sites More sharing options...
ayok Posted February 23, 2012 Author Share Posted February 23, 2012 You can't use aliases in WHERE clauses - pretend that aliasing happens after the conditions. HAVING doesn't have that restriction. SELECT *, (original_price - price) AS profit FROM items HAVING profit <= 50.00 ORDER BY RAND() While I'm at it, 1. If a number is supposed to be a number, don't put quotes around it. 2. Are you sure you want to ORDER BY RAND()? Do you actually want all of the results in a random order? Or do you just want a couple of them chosen randomly? Thanks.. I've tried using HAVING, and still got error. Can't I have HAVING and WHERE in a query? Yes I plan to display those randomly. Link to comment https://forums.phpfreaks.com/topic/257578-select-the-difference-between-2-column/#findComment-1320327 Share on other sites More sharing options...
ayok Posted February 23, 2012 Author Share Posted February 23, 2012 Ah.. it works! Thanks! Link to comment https://forums.phpfreaks.com/topic/257578-select-the-difference-between-2-column/#findComment-1320331 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.