0

Re all,

I need a little help with SQL. I got two SQL queries:

the first one counts how many occurences of a certain condition:

SELECT COUNT(*) 
FROM table1
WHERE condition1 = @condition

the second one select each row that match the same condition on the same table joined with a secondary table:

SELECT *
FROM table1 INNER JOIN table2
ON table2.id = table1.id_sub
WHERE condition1 = @condition

Using both these queries in interactive fashion (by code) I can achieve the result I need but I want to optimize the procedure using SQL features instead coding.

What I really need is a query that reports just a single row for each group of rows that matches condition1. I need also to insert the count of the matching rows as a field of the result row.

I'm running MySQL 5.6 and code the application trough Visual Studio 2013 Pro coding in C# (using MySQL.Data package).

Best Regards, WeirdGyn

2
  • Of course I need only the SQL code. Commented Jan 16, 2015 at 16:52
  • I've written a possible answer but without further clarification on your table structures and what columns you need to return it's hard to say if these answer will be what you're looking for. Commented Jan 16, 2015 at 17:00

1 Answer 1

1

All you need to do is GROUP BY the condition1 field. It would also appear that if you just need the COUNT by group that you wouldn't need the join.

SELECT condition1, COUNT(*)
FROM table1
--INNER JOIN table2
--    ON table1.id_sub = table2.id
GROUP BY condition1
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry but I forgot to mention that condition1 (in the second query) is based on data from table2 (that's why I need INNER JOIN).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.