AVG/COUNT MySQL query NOT working - mysql

I am not very experienced in MySQL queries so I might be doing something wrong.
Simplified my query is like this:
SELECT item.*, AVG(itemRating.rating) as 'rating', COUNT(itemRating.rating) as 'ratingCount'
FROM item, itemRating
WHERE item.id IN (...)
AND itemRating.item_fk = item.id
GROUP BY itemRating.item_fk
It works fine, except for when an item has no rating (no record in the itemRating table). Is there any way I can solve this without losing information?

SELECT item.id,
AVG(itemRating.rating) as 'rating',
COUNT(itemRating.rating) as 'ratingCount'
FROM item
LEFT JOIN itemRating ON itemRating.item_fk = item.id
WHERE item.id IN (...)
GROUP BY item.id

Related

MySQL join between two columns with case condition

i have an table with data which has both category and subcategory data in it.
So what is category and sub-category? category is the parent and sub-category is the child. Both data is similar except for one difference, parent_id for sub_category is id of the category.
Sample Data:
What is required?
sub-category name in the result should be category-name +'-'+ sub-category-name
Sample Result:
What is my attempt to solve the problem?
MySQL query which i have returning is done only to extract the sub-category only with the names:
SELECT
CONCAT(wcfc1.feed_category_name,
'-',
wcfc2.feed_category_name) AS feed_category_name,
wcfc2.feed_category_id,
wcfc2.parent_id,
wcfc2.category_type_id
FROM
wc_feed_categories wcfc1
JOIN
wc_feed_categories wcfc2 ON wcfc1.feed_category_id = wcfc2.parent_id;
This query is showing only:
i'm not able to figure out, how to write a query to show both category and sub-category with the name change in a single query.
Instead of
JOIN
wc_feed_categories wcfc2 ON wcfc1.feed_category_id = wcfc2.parent_id;
try
LEFT JOIN
wc_feed_categories wcfc2 ON wcfc1.parent_id = wcfc2.feed_category_id;
so your query will be:
SELECT
CASE
WHEN wcfc1.parent_id = 0 THEN wcfc1.feed_category_name
ELSE
CONCAT(wcfc2.feed_category_name, -- parent category
'-',
wcfc1.feed_category_name) -- child category
END AS feed_category_name,
wcfc1.feed_category_id,
wcfc1.parent_id
FROM
wc_feed_categories wcfc1
LEFT JOIN
wc_feed_categories wcfc2 ON wcfc1.parent_id = wcfc2.feed_category_id;
Demo here

Multiple count and left joins in MySQL Node using knex

I am trying to query posts and use 'count' to get the total amount of comments and likes to display. My query looks like this
const posts = await knex
.from("posts")
.select("posts.id as id", "posts.text", "posts.user_id")
.leftJoin("comments", "comments.post_id", "posts.id")
.count("comments.post_id as comments")
.leftJoin("likes", "likes.post_id", "posts.id")
.count("likes.post_id as likes")
.groupBy("posts.id");
res.send(posts);
However, I get different results if I exclude comments or likes and do something like this:
const posts = await knex
.from("posts")
.select("posts.id as id", "posts.text", "posts.user_id")
.leftJoin("comments", "comments.post_id", "posts.id")
.count("comments.post_id as comments")
.groupBy("posts.id");
res.send(posts);
I feel like I am doing something wrong. What is the correct way to chain multiple 'count' and 'leftJoins'?
Firstly start with SQL query and then convert it to Knex.
As #nbk said, when you joining the comments at the final result you will receive a row for each comment.
One option is using sub-query in select, the query will look like:
Select posts.id as id, posts.text, posts.user_id,
(Select count(*) from comments where comments.post_id=posts.id) as comments,
(Select count(*) from likes where likes.post_id=posts.id) as likes,
From posts;
This query can be converted to Knex:
const posts = await knex
.from('posts')
.select(
'posts.id as id',
'posts.text',
'posts.user_id',
knex('comments')
.count('*')
.whereRaw('?? = ??', ['comments.post_id', 'posts.id'])
.as('comments'),
knex('likes').count('*').whereRaw('?? = ??', ['likes.post_id', 'posts.id']).as('likes')
);

Hibernate - How can i perform UNION and return a LIST of items?

How can i run a UNION query in hibernate.
I'm new to learning hibernate and now i have a named query like this,
<query>
SELECT product.defaultSk.name FROM Product product
WHERE product.defaultSk.name LIKE :name
AND product.defaultSk.activeStartDate <= :currentDate
AND (product.defaultSk.activeEndDate > :currentDate OR product.defaultSk.activeEndDate = null)
AND (product.archiveStatus.archived IS NULL OR product.archiveStatus.archived = 'N')
UNION
SELECT category.name FROM Category category
WHERE category.name LIKE :name
AND (archived = 'N')
</query>
When i execute the above query, I'm getting the result for only the first query and my second query is not returning any results..
My console shows only the triggering of the first query and i cant find the second query being fired.Why does it not run the second query...
This my console after running the query,
CONSOLE:
Hibernate: select skimpl1_.NAME as col_0_0_ from PRODUCT productimp0_, BLC_SK skimpl1_ left outer join PRODUCT_SK_XREF skimpl1_1_ on skimpl1_.SK_ID=skimpl1_1_.SK_ID where productimp0_.DEFAULT_SK_ID=skuimpl1_.SK_ID and (skimpl1_.NAME like ?) and skimpl1_.ACTIVE_START_DATE<=? and (skimpl1_.ACTIVE_END_DATE>? or skimpl1_.ACTIVE_END_DATE is null) and (productimp0_.ARCHIVED is null or productimp0_.ARCHIVED='N')
I have implemented the jquery autocomplete to yeild results from a table and now that i want to merge two table results.I m going with the union query as it merges the result from two tables.
Am i doing something wrong..
I have read some SO posts that union is not possible in Hibernate.
If so what will be the workaround for this problem.
Thanks in advance.
HQL doesn't support union. You'll have to execute two different queries, or use SQL.

NHibernate INNER JOIN on a SubQuery

I would like to do a subquery and then inner join the result of that to produce a query. I want to do this as I have tested an inner join query and it seems to be far more performant on MySql when compared to a straight IN subquery.
Below is a very basic example of the type of sql I am trying to reproduce.
Tables
ITEM
ItemId
Name
ITEMRELATIONS
ItemId
RelationId
Example Sql I would Like to create
Give me the COUNT of RELATIONs for ITEMs having a name of 'bob':
select ir.itemId, count(ir.relationId)
from ItemRelations ir
inner join (select itemId from Items where name = 'bob') sq
on ir.itemId = sq.itemId
group by ir.itemId
The base Nhibernate QueryOver
var bobItems = QueryOver.Of<Item>(() => itemAlias)
.Where(() => itemAlias.Name == "bob")
.Select(Projections.Id());
var bobRelationCount = session.QueryOver<ItemRelation>(() => itemRelationAlias)
.Inner.Join(/* Somehow join the detached criteria here on the itemId */)
.SelectList(
list =>
list.SelectGroup(() => itemRelationAlias.ItemId)
.WithAlias(() => itemRelationCountAlias.ItemId)
.SelectCount(() => itemRelationAlias.ItemRelationId)
.WithAlias(() => itemRelationCountAlias.Count))
.TransformUsing(Transformers.AliasToBean<ItemRelationCount>())
.List<ItemRelationCount>();
I know it may be possible to refactor this into a single query, however the above is merely as simple example. I cannot change the detached QueryOver, as it is handed to my bit of code and is used in other parts of the system.
Does anyone know if it is possible to do an inner join on a detached criteria?
MySql 5.6.5 has addressed the performance issue related to the query structure.
See here: http://bugs.mysql.com/bug.php?id=42259
No need for me to change the output format of my NHibernate queries anymore. :)

MySQL COUNT() causing empty array() return

MySQL Server Version: Server version: 4.1.14
MySQL client version: 3.23.49
Tables under discussion: ads_list and ads_cate.
Table Relationship: ads_cate has many ads_list.
Keyed by: ads_cate.id = ads_list.Category.
I am not sure what is going on here, but I am trying to use COUNT() in a simple agreggate query, and I get blank output.
Here is a simple example, this returns expected results:
$queryCats = "SELECT id, cateName FROM ads_cate ORDER BY cateName";
But if I modify it to add the COUNT() and the other query data I get no array return w/ print_r() (no results)?
$queryCats = "SELECT ads_cate.cateName, ads_list.COUNT(ads_cate.id),
FROM ads_cate INNER JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName ORDER BY cateName";
Ultimately, I am trying to get a count of ad_list items in each category.
Is there a MySQL version conflict on what I am trying to do here?
NOTE: I spent some time breaking this down, item by item and the COUNT() seems to cause the array() to disappear. And the the JOIN seemed to do the same thing... It does not help I am developing this on a Yahoo server with no access to the php or mysql error settings.
I think your COUNT syntax is wrong. It should be:
COUNT(ads_cate.id)
or
COUNT(ads_list.id)
depending on what you are counting.
Count is an aggregate. means ever return result set at least one
here you be try count ads_list.id not null but that wrong. how say Myke Count(ads_cate.id) or Count(ads_list.id) is better approach
you have inner join ads_cate.id = ads_list.category so Count(ads_cate.id) or COUNT(ads_list.id) is not necessary just count(*)
now if you dont want null add having
only match
SELECT ads_cate.cateName, COUNT(*),
FROM ads_cate INNER JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName
having not count(*) is null
ORDER BY cateName
all
SELECT ads_cate.cateName, IFNULL(COUNT(*),0),
FROM ads_cate LEFT JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName
ORDER BY cateName
Did you try:
$queryCats = "SELECT ads_cate.cateName, COUNT(ads_cate.id)
FROM ads_cate
JOIN ads_list ON ads_cate.id = ads_list.category
GROUP BY ads_cate.cateName";
I am guessing that you need the category to be in the list, in that case the query here should work. Try it without the ORDER BY first.
You were probably getting errors. Check your server logs.
Also, see what happens when you try this:
SELECT COUNT(*), category
FROM ads_list
GROUP BY category
Your array is empty or disappear because your query has errors:
there should be no comma before the FROM
the "ads_list." prefix before COUNT is incorrect
Please try running that query directly in MySQL and you'll see the errors. Or try echoing the output using mysql_error().
Now, some other points related to your query:
there is no need to do ORDER BY because GROUP BY by default sorts on the grouped column
you are doing a count on the wrong column that will always give you 1
Perhaps you are trying to retrieve the count of ads_list per ads_cate? This might be your query then:
SELECT `ads_cate`.`cateName`, COUNT(`ads_list`.`category`) `cnt_ads_list`
FROM `ads_cate`
INNER JOIN `ads_list` ON `ads_cate`.`id` = `ads_list`.`category`
GROUP BY `cateName`;
Hope it helps?