Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Count on many to many

Tags:

sql

mysql

I have three tables

post

id | statement | date

features

id | feature

post_feature (many to many table between Post and Feature)

post_id | feature_id

I want to fire a query that will give me count of different distinct features and its respective features for the posts that are in given date period. I have just started learning SQL and I am not able to crack this one.

I tried the following one but not getting correct results.

 SELECT f.feature, count(f.feature)
   FROM  post_feature l 
   JOIN  features f ON (l.featureid = f.id AND l.featureid IN (
   select post.id from post where post.date > 'some_date'))
   GROUP BY f.feature
like image 439
rishi Avatar asked Sep 16 '12 17:09

rishi


People also ask

How do I count multiple values in SQL?

You can count multiple COUNT() for multiple conditions in a single query using GROUP BY. SELECT yourColumnName,COUNT(*) from yourTableName group by yourColumnName; To understand the above syntax, let us first create a table.

Can you GROUP BY count in SQL?

SQL – count() with Group By clause The count() function is an aggregate function use to find the count of the rows that satisfy the fixed conditions. The count() function with the GROUP BY clause is used to count the data which were grouped on a particular attribute of the table.

Can we use count on multiple columns in SQL?

You can GROUP BY multiple columns, to get the count of each combination.

What does count (*) do in SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.


1 Answers

You can try like this:

       SELECT f.feature, count(f.feature)
       FROM  post_feature l 
       JOIN  features f ON l.featureid = f.id 
       JOIN  post p ON l.post_id =p.id 
       WHERE p.date > 'some_date'
       GROUP BY f.feature
like image 117
Akash KC Avatar answered Sep 18 '22 23:09

Akash KC