When i join one table to another then i got this error. i put as keyword but its not working it give me error like field not found how can i solve this error
Code:
Product::leftjoin('reviews','products.id','=','reviews.productID')
->select(array('products.*',
DB::raw('AVG(rating) as ratings_average')
))
->where(function($query) use ($categoriesID,$brands,$priceArray,$ratingArray)
{
$query->whereIn('categoryID',$categoriesID);
if(count($brands) > 0)
{
$query->whereIn('brandID',$brands);
}
$query->whereBetween('productSellingPrice',$priceArray);
if(count($ratingArray) > 0)
{
$query->whereBetween('ratings_average',$ratingArray);
}
})
->groupBy('products.id')
->get();
Error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ratings_average' in 'where clause' (SQL: select `products`.*, AVG(rating) as ratings_average from `products` left join `reviews` on `products`.`id` = `reviews`.`productID` where (`categoryID` in (9, 11, 31) and `productSellingPrice` between 50 and 5000 and `ratings_average` between 1 and 2) group by `products`.`id`)
Instead of rating array you can find out $minRating and maxRating. By these two value you can run you query like this:
$query->whereBetween('rating',[$minRating,$maxRtaing]);
The problem is a SQL problem, and it has to do with scoping. I'm not well versed in laravel's API, but the SQL generated (based on your helpful error message) is:
select `products`.*, AVG(rating) as ratings_average
from `products` left join `reviews` on `products`.`id` = `reviews`.`productID`
where (`categoryID` in (9, 11, 31) and `productSellingPrice` between 50 and 5000
and `ratings_average` between 1 and 2) group by `products`.`id`)
The problem is that the ratings_average calculated column belongs to the GROUP BY scope. The only way to reference that column is in a HAVING statement. Your SQL statement would look like this:
select `products`.*, AVG(`ratings`.`rating`) as ratings_average
where `products`.`id` = `reviews`.`productId`
group by `products`.`id`
having (`categoryID` in (9, 11, 31) and `productSellingPrice` between 50 and 5000
and `ratings_average` between 1 and 2)
Technically speaking, the first two clauses in the having statement above could be in your WHERE clause, but the ratings_average named column can only be referenced in the HAVING clause. Both WHERE and HAVING restrict your results, but HAVING is evaluated after the grouping took place.
Related
When I run single exist query I get results as expected:
SELECT *
FROM `slasher_farming_mods`
WHERE EXISTS (SELECT * FROM `slasher_farming_brands`
WHERE `slasher_farming_mods`.`brand_id` = `slasher_farming_brands`.`id`
AND `brand_id` = '7'
ORDER BY `id` asc)
LIMIT 4 OFFSET 0
When I run multiple exist queries, I don't get any results:
SELECT *
FROM `slasher_farming_mods`
WHERE EXISTS (SELECT * FROM `slasher_farming_brands`
WHERE `slasher_farming_mods`.`brand_id` = `slasher_farming_brands`.`id`
AND `brand_id` = '7'
ORDER BY `id` ASC)
AND EXISTS (SELECT * FROM `slasher_farming_brands`
WHERE `slasher_farming_mods`.`brand_id` = `slasher_farming_brands`.`id`
AND `brand_id` = '24'
ORDER BY `id` ASC)
LIMIT 4 OFFSET 0
Tried using debugbar in laravel to see if my query is taking too long, but it takes less than 1ms. What could be wrong here, I tried to run these query also directly inside phpmyadmin but still no results with more than one where exists.
Query is populated by foreach loop in laravel.
foreach ($brands as $brand){
$query->whereHas('brand', function($q) use ($brand){
$q->where('brand_id', '=', $brand)->orderBy('id');
});
}
}
Your query doesn't work because brand_id cannot be both 7 and 24 for a given record. You want "OR". It would be clearer to just use the expression brand_id in (7, 24) instead of the two separate sub-queries. There is no point in sorting the sub-query.
Alternatively, join the two tables:
select ...
from slasher_farming_mods m
join slasher_farming_brands b on m.brand_id = b.id
where brand_id in (7, 24)
LIMIT 4 OFFSET 0
I have try to display result only if content > 0
SELECT actors.*, (SELECT count(*) FROM `content_actors`
WHERE content_actors.actor = actors.record_id) AS getCount
FROM actors
If i try to add in query
WHERE getCount > 0
I will have error
Unknown column 'getCount' in 'where clause'
In MySQL, you can use a having clause:
SELECT actors.*,
(SELECT count(*) FROM `content_actors` WHERE content_actors.actor = actors.record_id) AS getCount
FROM actors
HAVING getCount > 0;
This is a MySQL extension.
Assuming actors.record_id is unique (presumably a primary key), this could be written as:
SELECT a.*, COUNT(*) as getCount
FROM actors a JOIN
content_actors ca
ON ca.actor = a.record_id
GROUP BY a.record_id; -- assumes this is unique/primary key
No filtering is needed, because the JOIN requires at least one match.
Running the following MySQL Query and am getting this error:
database error Unknown column 'qd.ItemListID' in 'on clause'
SELECT
IFNULL(hqp.IsActive, qd.ItemName) AS Item_Name, DATE_FORMAT(IFNULL(hqp.SalesDate, qd.SalesDate), '%m-%d-%Y') AS effectDate, IFNULL(hqp.NoBid, qd.NoBid) AS noBid, IFNULL(hqp.VendorName, qd.VendorName) AS vendor, IFNULL(hqp.Source, qd.Source) AS source, IFNULL(hqp.Type, qd.Type) AS type, IFNULL(hqp.Cost, qd.PurchaseCost) AS cost, IFNULL(hqp.Price, qd.SalesPrice) AS price, IFNULL(hqp.ConditionCode, '') AS conditionCode, qi.UnitOfMeasureSetRef_FullName AS uom
FROM wp_quantum_data AS qd, wp_hunter_quote_parts AS hqp
LEFT JOIN wp_quickbook_items AS qi ON (qi.ListID = IFNULL(qd.ItemListID, hqp.Item_ListID))
WHERE qd.IsActive = 1 || hqp.IsActive = 1
GROUP BY Item_Name
ORDER BY Item_Name ASC
The column exists in the wp_quantum_data table so I can't explain why this error is occurring. I've tried renaming the column in phpmyadmin by typing the column name in and saving the column structure, but it is still saying that the column doesn't exist.
The problem is that you're mixing the archaic implicit JOIN syntax with LEFT JOIN. The LEFT JOIN only combines with the table immediately before it, which is wp_hunter_quote_parts; you can't refer to columns in wp_quantum_data in the ON clause.
You should get out of the habit of using implicit joins, and use explicit JOIN clauses for everything.
You also seem to have your joins in the wrong order. Since the row can be missing in wp_hunter_quote_parts, that's the table you should LEFT JOIN with.
SELECT
IFNULL(hqp.IsActive, qd.ItemName) AS Item_Name, DATE_FORMAT(IFNULL(hqp.SalesDate, qd.SalesDate), '%m-%d-%Y') AS effectDate, IFNULL(hqp.NoBid, qd.NoBid) AS noBid, IFNULL(hqp.VendorName, qd.VendorName) AS vendor, IFNULL(hqp.Source, qd.Source) AS source, IFNULL(hqp.Type, qd.Type) AS type, IFNULL(hqp.Cost, qd.PurchaseCost) AS cost, IFNULL(hqp.Price, qd.SalesPrice) AS price, IFNULL(hqp.ConditionCode, '') AS conditionCode, qi.UnitOfMeasureSetRef_FullName AS uom
FROM wp_quantum_data AS qd
LEFT JOIN wp_quickbook_items AS qi ON qi.ListID = qd.ItemListID
LEFT JOIN wp_hunter_quote_parts AS hqp ON qi.ListID = hqp.ItemListID AND hqp.IsActive = 1
WHERE qd.IsActive = 1
GROUP BY Item_Name
ORDER BY Item_Name ASC
I have one mysql query but when i'm trying to work showing me that error
Unknown column 'ps_address.phone_mobile' in 'field list'
Mysql Query is
SELECT
ps_orders.id_customer,
ps_customer.firstname,
ps_customer.lastname,
ps_customer.email,
ps_orders.total_paid,
ps_orders.date_add,
ps_address.phone_mobile
FROM
ps_orders JOIN ps_customer on ps_orders.id_customer = ps_customer.id_customer
WHERE ps_address.id_customer=ps_orders.id_customer and
ps_orders.total_paid > 1
AND ps_orders.id_customer IN (
SELECT
ps_orders.id_customer
FROM
ps_orders
GROUP BY
ps_orders.id_customer
HAVING
COUNT(1) < 2
)
You need to specifiy the table you're selecting FROM. So if the column exists, here's the updated query (abbreviated):
SELECT
ps_orders.id_customer,
ps_customer.firstname,
ps_customer.lastname,
ps_customer.email,
ps_orders.total_paid,
ps_orders.date_add,
ps_address.phone_mobile
FROM
ps_address, ps_orders
JOIN
ps_customer on ps_orders.id_customer = ps_customer.id_customer
WHERE
ps_address.id_customer=ps_orders.id_customer AND
ps_orders.total_paid > 1 AND
ps_orders.id_customer IN (...)
This syntax error means, you do not have this column "phone_mobile" in this table "ps_address".
The column does simply not exist?
Your script has syntax error. Column name "1" does not really exists in
COUNT(1) < 2
must be: COUNT(column_name) < 2
or COUNT(*) <2
COUNT(ps_orders.id_customer) < 2
I am using an alias in my select clause (AVG(u.rating) as avg_rating) and would then like to add this in my where clause avg_rating > 3 but when I try and run this query I get a Unknown column 'u3__1' in 'where clause'.
Does anyone happen to know how I can get my where clause to see the alias? This alias works in the orderBy with no issue, just not the where.
EDIT: (for more details)
The above was an example, but here is the real rendered SQL, not as simple. My issue is actually with an alias on value with a bunch of conditionals. And the alias I am having trouble with is the generated date which has recurrences and doesn't have to every date field populated. So I am posting a simple SQL query that gives me the same issue.
SELECT t.type_id as type_alias, t.* FROM theme as t WHERE t.id > 1 AND type_alias = 3
And here is the real query if you are so interested:
SELECT t.id AS t__id, t.created_by AS
t__created_by, t.type_id AS
t__type_id, t.url_slug AS t__url_slug,
t.name AS t__name, t.description AS
t__description, t.summary AS
t__summary, t.start_month AS
t__start_month, t.start_day AS
t__start_day, t.start_year AS
t__start_year, t.duration_unit AS
t__duration_unit, t.duration_length AS
t__duration_length, t.is_active AS
t__is_active, t.is_public AS
t__is_public, t.needs_moderation AS
t__needs_moderation, t.recurrence AS
t__recurrence, t.tag_string AS
t__tag_string, t.date_created AS
t__date_created, t.date_updated AS
t__date_updated, AVG(t2.rating) AS
t2__0, IF(t.recurrence = "none",
STR_TO_DATE(CONCAT(t.start_month,
t.start_day, t.start_year), "%m%d%Y"),
(IF(STR_TO_DATE(CONCAT(t.start_month,
t.start_day, YEAR(NOW())), "%m%d%Y") >
NOW(),
STR_TO_DATE(CONCAT(t.start_month,
t.start_day, YEAR(NOW())), "%m%d%Y"),
STR_TO_DATE(CONCAT(t.start_month,
t.start_day, (YEAR(NOW())+1)),
"%m%d%Y")))) AS t__1, (COUNT(u.id) +
COUNT(e.id)) AS u__2 FROM theme t LEFT
JOIN theme_rating t2 ON t.id =
t2.theme_id LEFT JOIN
user_saves_themes u ON t.id =
u.theme_id LEFT JOIN event e ON
((e.is_active = 1 AND e.theme_id =
t.id)) WHERE t.id IN ('3', '2', '1')
AND (IF(t.recurrence = "none",
STR_TO_DATE(CONCAT(t.start_month,
t.start_day, t.start_year), "%m%d%Y"),
(IF(STR_TO_DATE(CONCAT(t.start_month,
t.start_day, YEAR(NOW())), "%m%d%Y") >
NOW(),
STR_TO_DATE(CONCAT(t.start_month,
t.start_day, YEAR(NOW())), "%m%d%Y"),
STR_TO_DATE(CONCAT(t.start_month,
t.start_day, (YEAR(NOW())+1)),
"%m%d%Y")))) >=
FROM_UNIXTIME(1278001295) AND
t.is_public = ? AND t.is_active = ?)
GROUP BY t.id ORDER BY t__1
Look at this:
http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html
Standard SQL disallows references to column aliases in a WHERE clause.
This restriction is imposed because when the WHERE clause is
evaluated, the column value may not yet have been determined. For
example, the following query is illegal:
Either you have to add HAVING clause or repeat your alias in WHERE clause.
Try having instead of where.