Query in three tables by a column with Foreign Key

Asked

Viewed 604 times

2

This was the way I found to make a query in my three tables: PARENTS, CHILDREN and GRANDCHILDREN using the operator LIKE:

SELECT `PAIS`.nome,
       `FILHOS`.nome,
       `NETOS`.nome 
 FROM  `PAIS`, `FILHOS`, `NETOS`
 WHERE `PAIS`.nome LIKE '%MATILDE%'
 OR    `FILHOS`.nome LIKE '%MATILDE%' 
 OR    `NETOS`.nome LIKE '%MATILDE%'

I have another question related to the problem: recursive query in related tables using Foreign Keys

Just to recap, I’m going over the definitions of how my database is doing again (see image below):

Note that the table FLHOS is related to the table PARENTS by the column idPAI, in the case JOSE is the son of SEVERINO and MARIA is the daughter of JOSEFINA:

Now the question that won’t shut up: how do I bring this relationship of id with the person’s name through the word search '%MATILDE%' using the operator LIKE?

Example:

MATILDE idFILHOS 1 means that she is the daughter of JOSE, who is the son of SEVERINO, did you understand? I want to make this "recursion" seeking nome, but bringing only those who are related by the primary key id.

  • And the grandchildren table? Did not put

  • That’s a many table for many. I did a little exercise now that is able to help you. You need to create a pivot table that will store id_parent, and id_child only, so you can relate

  • @Miguel and the first from the bottom up

  • I edited the question because "phpmyadmin" is not a "database", read this to understand the differences: What is the difference between mysql and phpmyadmin?

1 answer

1


Hello, you need to list the primary and foreign keys of the tables... Make an INNER JOIN.

NOTE: I put JOIN wrong. Follow correct code:

SELECT 
  PAIS.nome,
  FILHOS.nome, 
  NETOS.nome 
FROM PAIS 
INNER JOIN FILHOS 
  ON PAIS.id = FILHOS.idPAI 
INNER JOIN NETOS ON FILHOS.idPAI = NETOS.idFILHOS
WHERE 
  PAIS.nome LIKE '%MATILDE%' OR FILHOS.nome LIKE '%MATILDE%' OR NETOS.nome LIKE '%MATILDE%'
  • face almost worked only have a syntax error that I can’t identify and pk and fK is already configured #1064 - You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near '.idFILHHOS WHERE PARENTS.name LIKE '%MATILDE%' OR CHILDREN.name LIKE '%MATILDE% OR NETOS.name LIKE '%MATILDE% at line 1' I don’t know if I’m wrong but it seems that INNER JOIN does not work in conjunction with WHERE

  • 1

    @Nikobellic Change the latest INNER JOIN > INNER NETOS JOIN FILHOS.id = NETOS.idFilhos. Elle forgot to put the table name in the latest INNER JOIN.

  • 1

    oh gee now it worked better even now I know how the INNER JOIN works guys really worth anything I can help too so there

Browser other questions tagged

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