How to use a Join clause by adding a column indicating the existence of a connection

Asked

Viewed 48 times

0

I have two tables

Horas (id, aluno_id, atividade_id)

and

Atividades (id, emblema_id)

In addition to returning all the badges, I need to return a column that tells me if that student has it. To know if he has, just that he has earned hours in activity.

Of the two ways that I tried, I was able to return only the emblems that he had and all the emblems at once, but without discriminating which one he actually had. As an example of the tables Hours and Activities filled, respectively, follows:

id | aluno_id | atividade_id
1  |    1     | 1


id | emblema_id
1  | 1
2  | 2

The expected result should be:

emblema_id | possui
    1      | Sim
    2      | Não
         ...

In the above expected result example, I demonstrate that the student has badge 1 because he has earned hours in the corresponding activity. However, it does not have the emblem 2, as it did not gain hours.

  • How will I know how to join the tables? Put the exact structure of them and some 3 example data for us can mirror more accurately

  • How to join tables? In the hours table the activity attribute corresponds to the activity id

  • @Cayodasilvalima As for the exact structure of the table, the relevant data are the same. I added an example of the populated tables that matches the expected result. See if it’s enough. Quan

  • @Marceloaugusto your question is not clear enough. Post the way you are doing.

1 answer

0

Make a LEFT JOIN and put a if to check whether the b.id is void or not:

SELECT a.`emblema_id`, IF(b.`id` IS NOT NULL, "SIM", "NÃO") AS 'possui' FROM `Atividades` a
LEFT JOIN `Horas` b ON a.`id` = b.`atividade_id` AND b.`aluno_id` = 1
GROUP BY b.`aluno_id`, b.`atividade_id`;
  • Only one error was presented. You used b.emblema_id, but did not refer to b outside of sub-select. I tried to modify but did not return the expected result.

  • I changed the SELECT, see if it now answers

  • The column was created as I said, but only the emblems that the student conquered were returned. Note that in the expected result the badge he did not conquer is marked as 'No'

  • I did it upside down, I’m gonna fix it

  • See now if it works

  • Presented error, I believe it corresponds to some column that is missing in group by

  • Which error you made?

  • Now I changed, I had to take the where and place the student check in the ON.

  • The error remained. Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'minhazoras.a.emblema_id' which is not functionally dependent on Columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

  • I made a change in group by and apparently returned as I expected. I put group by pro b.emblema_id and 'has'

Show 5 more comments

Browser other questions tagged

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