Note you should always include the full table schema and example data, as it'll make your questions clearer.
In general, to include fields not in the GROUP BY
clause in the SELECT
list, you should be using an aggregate function, like so:
SELECT
b.tableA_id,
MAX(b.id) AS max_b_id -- Choose whichever aggregate function makes sense here
from tableB b
INNER JOIN tableA
ON b.tableA_id = tableA.id
GROUP BY b.tableA_id
LIMIT 20
This will allow you to return values from the ungrouped columns, and your GROUP BY
clause will still de-dupe the records the same as it was before. Note you have to choose which aggregate function makes the most sense for the ungrouped column you want to SELECT
. Above I chose the MAX()
function as an example, which will just return the largest b.id
in this case. If you want the lowest b.id
then use the MIN()
function, etc.
Without knowing the rest of the fields in your tables or seeing sample data, I'm not sure what the goal of your query is. It'll also return a nondeterminsitic (random) 20 rows whenever you run it because you've specified a LIMIT
without an ORDER BY
clause.
Also, please don't use SELECT *
, it is an anti-pattern. Always explicitly list out only the columns you need from the query. That is how you were receiving the error of your question, because *
causes it to try to SELECT
ungrouped columns.
Perhaps you don't even want to return the b.id
column, and by explicitly listing out the columns names, you don't even need to include it. (Again, not sure what the goal of your query is?) So you could remove it from my example query, if that's the case.