need to get result of joining multiple tables as one row - php

I want to get result of joining multiple tables as one row and fetch multiple cuisine_name from t_cuisine table and get the cuisine_id in t_search.cuisineId column using php (CODEIGNITER) and joins
t_search table to get the cuisineId like this so that I can get the available cuisine names through the cuisineId.
t_search table
searchID|restaurant_name|cuisineId
1 | XYZ | 1,4,5
2 | KIH | 2
3 | GHY | 4,5
4 | UIO | 1,2,3
5 | RTY | 3,5
t_cuisine table
cuisineId|cuisine_name
1 | ABC
2 | CDE
3 | EFG
4 | GHZ
5 | HJL
in my Model i've used
$this->db->select('*');
$this->db->from('t_search');
$this->db->join('t_cuisine','t_cuisine.cuisineId = t_search.cuisineId');
which fetches data only based on single value in cuisineId in t_search.

$this->db->select('*');
$this->db->from('t_search');
$this->db->join('t_cuisine','t_cuisine.cuisineId IN(t_search.cuisineId)');
$this->db->where('t_cuisine.cuisineId', X);
Change X to the ID of the cuisine you are looking for

What you had previously (when your query worked based on a single value in cuisineId) was a one to many relationship. Joining like that worked well because each search had one cuisine.
This is a many to many relationship, and this table structure doesn't support it well. Instead of storing a delimited list in the cuisineId column of your t_search table, you need another table to represent the relationship between search and cuisine, like this:
t_search_cuisine table
searchID|cuisineId
1 | 1
1 | 4
1 | 5
2 | 2
3 | 4
3 | 5
4 | 1
4 | 2
4 | 3
5 | 3
5 | 5
Then you should be able to get all your data with one additional join.
$this->db->select('*');
$this->db->from('t_search');
$this->db->join('t_search_cuisine','t_search.searchID = t_search_cuisine.searchID');
$this->db->join('t_cuisine','t_search_cuisine.cuisineId = t_cuisine.cuisineId');

Based on the structure of your table, joining those table would be not easy. Perhaps you could do with two queries instead.
$this->db->select("cuisineId");
$this->where("searchID", $searchID);
$qry1 = $this->db->get("t_search");
$res1 = $qry1->row_array();
$qry1->free_result();
if ($res1) {
$this->db->select("*");
$this->db->where_in('cuisineId', $res1);
$qry2 = $this->db->get("t_cuisine");
$res2 = $qry2->result();
return ($res2) ? $res2 : false;
}

Related

Postgres, get all items from one table which ids are not in another tables JSON array column?

I have two tables:
cars table which contains:
id | name
1 | Audi
2 | Mercedes
3 | BMW
electric_cars
id | cars_id | non_valid_cars (json)
1 | 1 | [1,3]
2 | 3 | [1]
3 | 2 | [2,3]
How to select all records from the cars table which are not in the non_valid_cars array of ids in the electric_cars column with id cars_id?
Also, I am using Laravel Framework, but I will translate a query into the framework.
You can use a NOT EXISTS condition:
select c.*
from cars c
where not exists (select *
from electric_cars ec
where ec.non_valid_cars::jsonb #> to_jsonb(c.id)
and ec.cars_id = c.id);
Note that the use of jsonb is recommended over json so you might want to change that to avoid the casting.

Laravel Eloquent GroupBy Name to Create array of ID's

I have a table in my Laravel application which I wish to query.
id | company_name | contact |
-----------------------------
1 | Tesco | Name 1 |
2 | Tesco | Name 2 |
3 | Asda | Name 3 |
4 | Tesco | Name 4 |
5 | Asda | Name 5 |
I'm trying to get an array of all unique company names with all ID numbers.
'Tesco' => [1,2,4]
'Asda' => [3,5]
I have tried
$companies = Contact::select('company_name','id')->groupBy('company_name')->get();
However this requests the 'id' to be included in the group by which defeats the purpose. I understand it's asking for this because it's not a SUM or COUNT etc.
The above table may seem unusual and I know I should have a relation to a companies table however this is necessary at this stage.
You could use GROUP_CONCAT()
$companies = Contact::select('company_name', DB::raw('GROUP_CONCAT(id) as ids'))
->groupBy('company_name')
->get();
This would return something like:
company_name | ids
Tesco | 1,2
Edit: if you want the ids in the form an array, you could just map over the collection to convert it:
$companies->map(function($column) {
$column->ids = explode(',', $column->ids);
});
That should do the trick.

Retrieve rows from DB in groups according to a field using MySQL

imagine we have a table like :
item_id | item_name | item_group
--------|-----------|-----------
1 | foo | jgKleC
2 | bar | jgKleC
3 | hey | jgKleC
4 | bra | DskgvV
5 | car | DskgvV
What would be a convenient way to pull this data from the database using MySQL queries in PHP to achieve this result :
Array (2){
'jgKleC' = Array(3)[
Array(3)[1, foo, jgKleC],
Array(3)[2, bar, jgKleC],
Array(3)[3, hey, jgKleC]
],
'DskgvV' = Array(2)[
Array(3)[4, bra, DskgvV],
Array(3)[5, car, DskgvV]
]
}
I'm working in PHP and using arrays only would be a plus for me.
select item_group, Concat(item_id,',',item_name,',',item_group) ) as data from tableName
now you get this data in $result
$a='';
foreach($result as $result2){
$a[$result2['tableName]['item_group']] =array($result2['tableName]['data'])
}
now may be you can get the idea

DISTINCT * is not withdrawing the duplicity (MYSQL)

i already done everything to remove this duplicity on the database
On selecting a checkbox on the sectio "Bairros" i utilized as Array
for($m=0; $m<count($_POST["bairros"]); $m++){// LOOP 1
$pesquisar=($_POST["bairros"][$m]);
//Copy bairros(Array) and esporte (POST)
$query = "SELECT DISTINCT * FROM cadastro WHERE
(esporte1 = '".$_POST["esportes"]."' OR
esporte2 = '".$_POST["esportes"]."' OR
esporte3 = '".$_POST["esportes"]."' OR
esporte4 = '".$_POST["esportes"]."')
AND
(bairro1 = '".$pesquisar."' OR
bairro2 = '".$pesquisar."' OR
bairro3 = '".$pesquisar."' OR
bairro4 = '".$pesquisar."')
AND
ativarAparecer='sim' ORDER BY nomeCompleto ASC LIMIT 20";
$esporte= new consultar();
$esporte->executa($query);
//Loops
for($l=0; $l<$esporte->nrw; $l++){ //LOOP 2
echo $esporte->data["nomeCompleto"]."<br />";
$esporte->proximo();
} //close LOOP2
} //close LOOP1
Detail: this function object oriented, I believe that i'm doing something wrong at SQL or MYSQL, perhaps something is missing there.
SELECT DISTINCT *
Stop There. DISTINCT * can do what? Duplicate of what? it cant do that. Give it a field name to see unique values.
For example
SELECT DISTINCT nomeCompleto
Let's break this down. The DISTINCT clause will return unique sets based on the selected columns.
Let's say you have a table:
a | b | c
=========
1 | 2 | 3
1 | 1 | 3
1 | 2 | 4
Now if you SELECT DISTINCT a FROM table, you would get:
1
but if you SELECT DISTINCT a, b FROM table, you would get:
a | b
=====
1 | 2
1 | 1
That's because {1,2} is different from {1,1}, even though the a column is the same between those two sets.
Obviously, doing SELECT DISTINCT * FROM table would give you the original table because it uses all three columns as a "composition" of the unique set. If we amended the table to look like this:
a | b | c
=========
1 | 2 | 3
1 | 1 | 3
1 | 2 | 4
1 | 2 | 3
Then your result of SELECT DISTINCT * FROM table would give:
a | b | c
=========
1 | 2 | 3
1 | 1 | 3
1 | 2 | 4
because of the duplicate result set of {1, 2, 3}. However, since most tables have an auto-incrementing identifier as the primary key, there is almost always no difference between SELECT * and SELECT DISTINCT *.
Perhaps you're looking to GROUP BY a certain column?
How would I be using GROUP this in my script? Column that there are several equal records are this bairro, bairro2, bairro3, bairro4. Inside it is in numbers
bairro1 | bairro2 | bairro3 | bairro4
14 | 14 | 15 | 27
34 | 15 | 14 | 30
27 | 45 | 12 | 14

count with doctrine

I have two table:
Name
id | name | city_id
1 | aaa | 1
2 | vvv | 2
3 | ddd | 2
4 | sss | 3
5 | dds | 1
etc
City:
id | name
1 | London
2 | NY
3 | Boston
etc
how can i get City and count:
name_city | count
London | 2
NY | 2
Boston | 1
In City table:
$q = $this->createQuery('a')
->leftJoin('a.Name n')
->select('a.name_city as name_city, sum(n.city_id) as sum');
return $q->execute();
but this is wrong.
You should use count() instead of sum(), and plus, you need a group by.
You do not appear to have a FROM clause, the object type is not specified for the a entity.
Also, read the aggregate values section in the documentation.
this post was kinda helpful but I though that I would add a little more details for anyone looking to join 2 tables and with an aggregate count.
e.g. this post (http://stackoverflow.com/questions/7837671/mysql-join-tables-and-count-instances) but in doctrine.
Using the example above the query would be (doctrine 2.0):
$q = $this->em->createQueryBuilder('a')
->select('a.name_city as name_city, count(n.city_id) as sum');
->from('city','a')
->leftJoin('a.Name n')
->groupBy('n.id')
->orderBy('sum')
$query = $qb->getQuery();
echo $qb->getDql(); // if you want to see the dql created
$result = $query->getResult();

Categories