-3

This gives me errors. How do I need to rewrite it?

I want to have the query return both the subject and that row's corresponding count.

SELECT (SELECT subject FROM marks) AS subject, (SELECT count FROM marks) AS count WHERE usr = 'username'

Nemo-Omen
  • 117
  • 9
  • 2
    What do you mean by "that row's corresponding count"? `count` is a function that counts rows; it doesn't work on one row. Or do you have a column named `"count"`? (If so, please rename the column to something other than a MySQL function name.) Can you give us an example (with data) of what you're trying to accomplish? – Ted Hopp Jan 02 '17 at 23:55
  • @TedHopp I will rename, thanks! – Nemo-Omen Jan 02 '17 at 23:59
  • Relevant question: http://stackoverflow.com/questions/2889871/how-do-i-escape-reserved-words-used-as-column-names-mysql-create-table – Ted Hopp Jan 03 '17 at 00:02
  • @TedHopp, `COUNT` is not a reserved keyword. – shmosel Jan 03 '17 at 00:06
  • @shmosel - No, but it's the same fix in the case of a column name being the same as a function name. – Ted Hopp Jan 03 '17 at 00:07
  • @TedHopp There's no problem with naming a column the same as a function name. [Proof](http://sqlfiddle.com/#!9/303612/1/0) – shmosel Jan 03 '17 at 00:11
  • @shmosel - How about that. I was obviously off on the wrong track. – Ted Hopp Jan 03 '17 at 00:12

2 Answers2

2

The subqueries are not required and are breaking your relationship. Try this:

SELECT subject, `count` FROM marks WHERE usr = 'username';

I think count is a column in your table? If so, as @TedHopp points out, since count is also a mysql built-in function, you'll have to escape it to refer to the column name.

http://sqlfiddle.com/#!9/e3cd1/1 is a corresponding fiddle.

Daniel Farrell
  • 11,706
  • 2
  • 25
  • 27
0
SELECT subject, COUNT(subject) `count`
FROM marks
WHERE usr = 'username'
GROUP BY subject
abigperson
  • 4,983
  • 3
  • 21
  • 25