How to select most used foreign key?

Asked

Viewed 16 times

0

I’d like to make one SELECT where to select foreign key(idTema) most used

Example:

inserir a descrição da imagem aqui

That in the example above would be 1

What would that be like SELECT?

2 answers

2

You have to group by idTema, sort by the quantity decreasing and limit in 1 record:

SELECT a.`idTema`, COUNT(*) qtde
FROM nome_da_tabela a
GROUP BY a.`idTema`
ORDER BY qtde DESC
LIMIT 1;

See more about GROUP BY here.

  • But then you’re always filtering 1, right? And if the most used idTema is another id and not 1. Wanted something general, you know?

  • I’m not limiting the idTema = 1 is to limit the number of lines that will be returned. This SELECT works pro general.

  • Got it, I’ll test it.

2


I don’t know if it’s the best way to build select but I think it solves.

SELECT idTema FROM nome.tabela GROUP BY idTema ORDER BY count(idTema) DESC LIMIT 1;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.