how to get count of another table - php

Like below image I have two tables, now I want to get all columns from Restaurant table depending on cat column, and number of records from Foods table that have that Restaurant id.
example : (to get 1,test from Restaurant table and 3 from Foods table).
$sql = "select * from Restaurant,Foods where cat=6..." ;
updated :
$sql = "r.*,(SELECT COUNT(*) FROM restaurant_foods WHERE restaurant_id = r.id)
foods_count FROM restaurant r WHERE r.cats LIKE '%,$cat,%' limit $start,$end"

That should do the job:
SELECT r.*,
(SELECT Count(*)
FROM Foods
WHERE restaurnat_id = r.id) foods_count
FROM Restaurant r
WHERE r.cat = 6

Related

select two tables and view in a table

I’ve a BD with the next tables.
TABLE detalle_contrato
TABLE detalle_tradicional
There is a relation with ID_CONTRATO and i need to view the table with the next data.
SELECT
ID_CONTRATO,
TRADICIONAL,
NOM_VARIEDAD,
SUM(CANTIDAD)
FROM detalle_contrato
WHERE ID_CONTRATO = '$ID' AND TIPO_VARIEDAD = 'TRADICIONAL';
SELECT
SUM(CANTIDAD_D)
FROM detalle_tradicional
WHERE ID_CONTRATO = '$ID'
GROUP BY NOM_VARIEDAD ";
There are a filter different in this two select and I need this in a table but i don't know together.
The idea is this:
ID_CONTRATO,
NOM_VARIEDAD,
CANTIDAD
( THIS IS THE SUM THE ALL CANTIDAD DUKE AND
LEGACY IN GROUP THE TABLE DETALLE_CONTRATO) ,
CANTIDAD_D
(TABLE DETALLE_TRADICIONAL THIS IS SUM
THE ALL DUKE AND LEGACY SEPARATE THE CANTIDAD_D
I need exactly this using the data the photos
You can use LEFT JOIN. Left join your second table with id_contrato and detalle_contrato id_contrato.
SELECT
dc.ID_CONTRATO,
dc.TRADICIONAL,
dc.NOM_VARIEDAD,
dc.IFNULL(SUM(CANTIDAD),0) AS CANTIDAD,
dc.IFNULL(SUM(CANTIDAD_D),0) AS CANTIDAD_D
FROM
detalle_contrato dc
LEFT JOIN TABLE_NAME t2 ON t2.ID_CONTRATO = dc.ID_CONTRATO
WHERE dc.ID_CONTRATO = '$ID' AND t2.TIPO_VARIEDAD = 'TRADICIONAL'

Add count from two queries in codeigniter?

I have 4 tables
I query:-
1. activity: having activity id
2. activity_specialties:having activity id and specialties
3. users: specialties
4. List item
II query:
activity: having activity id
icd10_assignments:activity_assignment_id
I have to find count from I query and II query
and add those count result to find total result
my columns are activity id and total count
My two queries are
1)
SELECT `activity`.`activity_id`, count(distinct users.id) as user_id
FROM (`activity`)
JOIN `activity_specialties` ON `activity`.`activity_id` = `activity_specialties`.`activity_id`
LEFT JOIN `users` ON `users`.`specialty`= `activity_specialties`.`specialties_id`
WHERE `activity_category` = 'Online CME Activities'
GROUP BY `activity`.`activity_id`
2)
SELECT `activity`.`activity_id`, count(icd10_assignments.id) as assign_id
FROM (`activity`)
JOIN `icd10_assignments`
ON `activity`.`activity_id`= `icd10_assignments`.`activity_assignment_id`
WHERE `activity_category` = 'Online CME Activities'
GROUP BY `activity`.`activity_id`

Statement to Count(*) related rows on other table

I have two tables named patient_list and dentist_list where in the dentist can have many patients, I want to get how many patients the dentist has and ordered it.
I have here a sample code where I get each patient of doctor:
$query_dentist = "SELECT * FROM dentist_list ORDER BY ID ASC";
$res_dentist = mysql_query($query_dentist);
if ($res_dentist) {
while ($row_dentist = mysql_fetch_array($res_dentist)) {
}
}
After I get all the dentists, I create a new query inside the while where I will get all the patient count.
$dentist_id = $row_dentist['id'];
$query_patient= "SELECT COUNT(*) as patient_num FROM patient_list
WHERE dentist_id ='$dentist_id'";
$res_patient=mysql_query($query_patient);
if($res_patient)
{
while($row_patient=mysql_fetch_array($res_patient))
{
}
}
For example the output of query is:
doctor 1 has 10 patient
doctor 2 has 5 patient
doctor 3 has 100 patient
Rather than using PHP, is it possible to use a MySQL statement instead? I will create one query only because i need it to sort by number of patient.
You can try using this code:
select d.Name, -- <- put dentist information here
(select count(1) from patient_list p where p.dentist_id = d.dentist_id)
from dentist_list d
order by 2 asc -- <- order by by the 2nd field that is (select count(1...
SELECT COUNT(*) AS Patient_Num FROM patient_list GROUP BY dentist_id ORDER BY 1

MySQL search with joins and match

I've got one table filled with information about companies (tblforetag) in Sweden, one table with provinces (tbllan) and one table with cities (tblstad). The cities are linked to the provinces with id numbers and the company table has a column for the city name (varchar).
How do I search for all the companies in one province?
I have fiddled around with joins but not got it to work. I've got this code right now that works but it will only search for company names and cities (in the company table):
$sql = "
SELECT *,
MATCH(tblforetag.foretag) AGAINST(:keywords) AS kr
FROM tblforetag
WHERE MATCH(tblforetag.foretag) AGAINST(:keywords)
";
$sql .= $locisset ? "AND tblforetag.stad LIKE :location" : "";
$sql .= " LIMIT $offset, $rpp";
$query = $conn->Prepare($sql);
$query->BindValue(':keywords', $keywords);
if($locisset) $query->BindValue(':location', "%$location%");
$query->Execute();
I do not know your table structure but something along these lines shoulod do the trick:
SELECT FROM companies
LEFT JOIN cities ON (companies.city_id = cities.id)
LEFT JOIN regions ON (cities.region_id = regions.id)
WHERE region.name = 'your region'
This would give you the companies in that particular region.
I think it would be better the city_name column in companies table to city_id.
SELECT a.*, p.provincename
FROM companies a, cities c, provinces p
WHERE a.city_name = c.city_name
AND c.city_id = p.city_id
AND p.province_id = 5 // give your province id here

PHP & MYSQL selection

Ok folks. I have a Table categories with id, categoryname.
categories has: id=1 categoryname = batteries, id=2 categoryname = flashes, id=3 categoryname glasses.
The Second table is users. Users have id, user_eimal, my_choices.
Every user has store into my_choices the category name that wants to appear.
So for example user George with user_email xxxxx#xxx.com has store in my_choices: batteries,glasses
Now i want to bring up records from table products where categoryname is the values that user george has stored into my_choices.
Products has id, p_title, categoryname
for example i want to:
<?php
$usenmail = $_SESSION['SESS_EMAYL_NAME'];
$q1 = "SELECT * FROM categories WHERE id = '$id'";
$q2 = mysql_query($q1, $connectiondb) or die(mysql_error());
$results = mysql_fetch_assoc($q2);
$my_choices = $results['my_choices']; //That means $my_choices = batteries,glasses
//Now i want to select fom my table poducts only the categories (batteries,glasses)that user has store.
$trt = mysql_query ("select * from products where categoryname = batteries,glasses");
while($apst = mysql_fetch_assoc($trt)) {
echo '<div style="color: #000; float: left;">Productname: '.$['apst'].'</div>';
echo '<br>';
}
?>
You want to use a join table so you can have a many-to-many relationship. Your current structure is better suited to each user only having ONE choice.
What you want are three tables:
Users (userID, user_name, user_email)
Categories (categoryID, category_name)
Users_Categories (userID, categoryID)
So to use your example, your three tables would look like this (if anyone knows a better way to demonstrate SQL tables on here, please let me know):
Users
userID: 1 | user_name: George | user_email: george#example.com
Categories
categoryID: 1 | category_name: batteries
categoryID: 2 | category_name= flashes
categoryID: 3 | category_nameglasses.
Users_Categories
userID: 1 | categoryID: 1
userID: 1 | categoryID: 3
You would then use a select statement with a join clause to get George and his categories:
SELECT
user_name,
category_name
FROM
Users
LEFT JOIN Users_Categories USING (userID)
LEFT JOIN Categories USING (categoryID)
WHERE
userID = 1
This would return two rows in the result:
George, Batteries
George, Glasses
Depending on what you want to do with that data, it may be better to also select the userID.
If you want a query that will only return one row with all of the information, it gets a little trickier. You have to use the GROUP BY functionality. That would look like this:
SELECT
user_name,
GROUP_CONCAT (category_name ',')
FROM
Users
LEFT JOIN Users_Categories USING (userID)
LEFT JOIN Categories USING (categoryID)
GROUP BY
userID
WHERE
userID = 1
For your final question about products, you would follow the same logic with more joins. Your Products table wants to have a productID, product_name, and categoryID.
$trt = mysql_query ("select * from products where categoryname = 'batteries' OR categoryname = 'glasses'");
Use explode function
$array = explode(','$my_choices);
now array[0] and array[1] have the 2 values. then use
$result = mysql_query ("select * from products where categoryname = '".$array[0]."' OR categoryname = '".$array[1]."'");
In your case use select statement as,
select * from products where categoryname in ( 'batteries','glasses');
ie,
//add quotes to category names (if ids you dont neeed these 2 lines)
$cats=explode(',',$my_choices);
$strcats = "'" . join("', '", $cats) . "'";
$trt = mysql_query ("select * from products where categoryname in ($strcats));
My suggestion to use category ids instead of category names.

Categories