How to relate the same table without conflict?

Asked

Viewed 50 times

0

I have a user table, and a likes table. The table of likes has: usuario_curtido and usuario_curtiu.

When I execute

select u.usuario_nome from usuarios u
JOIN te_curtidas_usuarios c
ON c.curtida_usuario_curtido = u.usuario_id
ORDER BY c.curtida_data LIMIT 15

users clash - I always get the same user.

Answer:

array(7) {
  [0]=>
  array(1) {
    ["usuario_nome"]=>
    string(11) "Maria Joana"
  }
  [1]=>
  array(1) {
    ["usuario_nome"]=>
    string(16) "Daniel Bonifacio"
  }
  [2]=>
  array(1) {
    ["usuario_nome"]=>
    string(16) "Daniel Bonifacio"
  }
  [3]=>
  array(1) {
    ["usuario_nome"]=>
    string(16) "Daniel Bonifacio"
  }
  [4]=>
  array(1) {
    ["usuario_nome"]=>
    string(16) "Daniel Bonifacio"
  }
  [5]=>
  array(1) {
    ["usuario_nome"]=>
    string(16) "Daniel Bonifacio"
  }
  [6]=>
  array(1) {
    ["usuario_nome"]=>
    string(15) "Daniel Oliveira"
  }
}

Table: Tabela de curtidas

  • 1

    use GROUP BY u.usuario_name. or better GROUP BY u.usuario_id

1 answer

3


Update

From what I understand you’re not relating the same table, you’re relating the table usuarios with te_curtidas_usuarios through JOIN. In this case they will return all occurrences of the second table curtida_usuario_curtido in which curtida_usuario_curtido is equal to usuario_id, repeating the names usuario_nome which are on the first table usuarios.

To prevent the same user from being repeated, you should group the result of the query by id user using GROUP BY:

select u.usuario_nome from usuarios u
JOIN te_curtidas_usuarios c
ON c.curtida_usuario_curtido = u.usuario_id
GROUP BY u.usuario_id
ORDER BY c.curtida_data LIMIT 15
  • 1

    This answer does not deal with the case of homonymous users. GROUP BY should group by user ID, or if only interested in the list of names, use DISTINCT instead of GROUP BY whose goal is to produce aggregates (sum, Count, etc.) and not remove distinct occurrences.

  • Because it "works".

  • @epx Hi friend. I made an update on the reply. See if you are now better. Obg and sorry for the jokes.

Browser other questions tagged

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