I have two functions where I make two queries and what I want is to join both queries but I can't find a way to do it.
I have a getLanguages() function:
public static function obtieneIdiomas()
{
$sql= "SELECT nombre as idiomas FROM idiomas";
$resultado=self::ejecutaConsulta($sql);
$arrayIdiomas=array();
while ($fila=$resultado->fetch(PDO::FETCH_ASSOC))
{
$arrayIdiomas[]= $fila["idiomas"];
}
return $arrayIdiomas;
}
And a getCandidate() function:
public static function obtieneCandidatos()
{
$sql2= "SELECT distinct c.dni, c.nombre, c.apellidos, c.sexo FROM candidatos c
inner join idiomas_encuesta i on c.dni=i.dni_candidato
inner join idiomas id on i.id_idioma=id.id;";
$resultado2=self::ejecutaConsulta($sql2);
$arrayCandidatos=array();
while ($fila=$resultado2->fetch(PDO::FETCH_ASSOC))
{
$arrayCandidatos[]=new Candidato ($fila);
}
return $arrayCandidatos;
}
In the controller I call these two functions to build the arrays:
$arrayDatosPersonas=ClaseBase::obtieneCandidatos();
$arrayIdiomasPersonas=ClaseBase::obtieneIdiomas();
And this is as far as I've been able to get:
This is the query that should output:
But without repeating the personal names, that is, in Miguel's Language field, French and Chinese must appear.
I've thought that maybe we should use the getCandidates function the getLanguages function but I have no idea how to do it. There is a table that shares the key between candidates and languages and I imagine that they will have to be compared in some way.
Let's see if you can give me a hand thanks.
PS: Thinking about it, maybe it's not necessary to use the getLanguages() function, maybe you could do two selects in getCandidate()?
You can get the results you want in a single query by using an aggregation function .
You don't state what database engine you're using. If you're using MySQL, that function is GROUP_CONCAT . If you use a different engine, it will have a function with similar characteristics at its disposal. Oracle for example has LISTAGG .
In this link you have a small example so you can see how it works with some test data, although I will also paste it here below.
Modifying the query that you include a bit, we obtain the expected result
Result with my data set reduced
Next time try to add to your question the structure of the tables (CREATE) and some set of test data (INSERT) so that whoever wants to help you can copy them and add them to their answer. You are always in time to edit and include this information.
BONUS
If you want the list of languages to be ordered, you have to apply an ORDER before applying the aggregation. Here I put another example query with the data ordered in another way.
bonus result