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
Related
I have "reservation" table (mySql) that contain number of columns: res_id, hotel_id, hotel_name, from_date, to_date.
I would like to select and print html table for each hotel (i'm using PHP). the result should be a title - the name of the hotel, and bellow it a list of reservation for the specific hotel.
I can do GROUP BY:
Select * FROM reservation GROUP BY hotel_id
I'm not sure if it's the right way to do it, and how do i print the results without checking all the time if the hotel_id was changed?
Thank you in advanced
GROUP BY is definitely NOT the right way to approach this. One method would be:
SELECT *
FROM reservation
ORDER BY hotel_id;
You would then loop through the result sets. When the hotel name changes, you would put in the title of the hotel.
Note: This is a poor data model if it has both the hotel id and name in reservation. This would normally be in hotel and you would connect the tables using JOIN:
SELECT h.hotel_name, r.*
FROM hotels h JOIN
reservation r
ON r.hotel_id = h.hotel_id
ORDER BY hotel_id;
Using a LEFT JOIN, you can even get hotels with no reservations.
How is it that the hotel_id would change? As per your question it seems that hotel_id is a column made for join with a "hotels" table, isn't it?
Regarding the "group by", why would you group by hotel? This would make you loose reservations data, unless you were using some sort of group_concat.
If you want to get the reservations from a specific hotel you could loop through your hotels table and inside your loop you can do:
SELECT * FROM reservations WHERE hotel_id='QUERIED_HOTEL_ID'
Then show the results.
Or you could simply
SELECT * FROM reservations
And when you get the fetched results you can make a multidimensional php array with 'hotel_id' as top level key and 'res_id' as secondary, like this:
$reservations_by_hotel = [];
do {
$resId = $row['res_id'];
$hotelId = $row['hotel_id'];
$reservations_by_hotel[$hotelId][$resId] = $row;
} while ($row = $result->fetch_assoc());
I have a MySQL table from which I want to extract attendance information(Student Id, course/subject for attendance, date range,whether the student was present or not). I have written the following query:
SELECT
COUNT(a_id),
(
SELECT COUNT(*) FROM attendance
WHERE state = 'present'
AND `dater` BETWEEN '$a' AND '$b'
) AS Count,
stud_id
FROM attendance
WHERE
stud_id =(SELECT id FROM users WHERE NAME = '$stud')
Which is giving me the correct results, but when I change the student,its not giving me the correct count for the days recorded for present. Not mention that I have not yet added the course parameter into the query
The MySQL table is as follows:
I need help for the query to return the desired results(Count the accurate days present for each student, as well as adding the course parameter into the query so that the query will look for attendance records for a specific course, for a specific student, for a specified date range).
Looks like you want to seperate your queries:
Select (select count(*) from <database>.attendance where state = 'present' AND (dater between '$a' and '$b') AND name=(SELECT id FROM users WHERE NAME = '$stud')) as present, (select count(*) from <database>.attendance where state = 'absent' AND (dater between '$a' and '$b') AND name=(SELECT id FROM users WHERE NAME = '$stud')) as absent from <database>.attendance WHERE stud_id =(SELECT id FROM users WHERE NAME = '$stud');
try this :)
Resolved it using JOIN as follows:
SELECT u.id, a.stud_id, a.course_id, count(*) FROM attendance a
JOIN users u ON u.id=a.stud_id
JOIN courses c ON c.c_id=a.course_id
WHERE a.state='present' and dater between '2017-09-01' and '2017-09-14'
GROUP BY a.stud_id, a.course_id;
Thanks for your help.
So I have a table where some of the products repeat with but have a different value on number of clicks.
name ---- clicks
iPhone 4
Samsung 2
iPhone 1
Samsung 5
my select function is :
$select_table2 = 'SELECT * FROM `mytable`'; //WHERE NAME IS THE SAME
$sql2 = $db->query($select_table2);
while ($row = mysqli_fetch_array($sql2)) {
echo $row["name"];
echo $row["clicks"];
}
I need this output:
iPhone 5
Samsung 7
I don't want to merge the same rows because they have one more column that is different. So please do not suggest simply to merge them and update the clicks...
UPDATE:
$pull_request = 'SELECT SUM(e.product_clicks),e.product_id, u.name, u.product_id FROM `oc_aa_affiliatecollclicktracking` AS e GROUP BY e.product_id LEFT JOIN `'.DB_PREFIX.'product_description` AS u ON e.product_id = u.product_id';
I tried it like this but it's not working
use sum() and also GROUP BY name to get desired output.
$select_table2 = 'SELECT name,SUM(clicks) FROM `mytable` GROUP BY name';
$sql2 = $db->query($select_table2);
while ($row = mysqli_fetch_array($sql2)) {
echo $row["name"];
echo $row["clicks"];
}
while will produce,
iPhone 5
Samsung 7
For more info
SUM()
GROUP BY
EDIT
Group by should come after join.
$pull_request = 'SELECT SUM(e.product_clicks) as clicks,e.product_id, u.name, u.product_id FROM `oc_aa_affiliatecollclicktracking` AS e
LEFT JOIN `'.DB_PREFIX.'product_description` AS u ON e.product_id = u.product_id
GROUP BY e.product_id';
You want to perform a SUM command by group
$query = "SELECT `name`,SUM(`clicks`) FROM `mytable` GROUP BY `name`";
Edit: The other answer was more complete than mine. I forgot to select name field. Added.
What you need is an aggregate function for suming the clicks [SUM(clicks)], and a Group By clause for defining the classification criteria [GROUP BY name].
The other answers where wrong in the sense that are assuming that by changing the select field list adding the aggregate 'SUM', the associative references (eg: index strings of the $row array ) remains the same, the correct query would be:
$select_table2 = 'SELECT name, SUM (clicks) AS clicks FROM mytable GROUP BY name';
Note the alias on SUM(clicks) AS clicks, so the fields returned in the array $row keep their indexes (clicks, names... instead of 'SUM(clicks)')
And the rest is basically the same.
Cheers!
Try :
$select_table2 = 'SELECT name, SUM (clicks) FROM mytable GROUP BY name';
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
Select 3 rows from table1
Get a specific column data out of each row.
Then use that each column data obtained , to make a query again to get data from table2.
Store the data obtained in step 4 into a variable for each row.
Then put them in json array (table 1 , 3 rows + table 2's data(each of them).
I am building a rank table, it displays top 3 users with their rank name.
For example:
User1 has 2000 points , user 2 has 4000points , user 3 has 10k points , so the top 3 user is :
user 3 > user 2 > user 1
So , i want the php to go to 'users' table and get the top 3 members using this:
$query = mysql_query("SELECT * FROM users ORDER BY pts DESC LIMIT 3");
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
Table structure for 'user':
1.username(varchar)
2.pts(int)
After the rows are put into an array , how can i get 'points' for each of the row in that array.
Then go to 'rank' table to get their ranknames.
Table structure for 'rank':
1.rank(varchar)
2.pts(int)
Inside rank table there is 'pts' to let php choose compare which rank the user is at based on the points from each row of the array.
Normally i would use this if its only for 1 user , but for multiple users , im not sure:
$result = mysql_query("SELECT * FROM rank WHERE pts <= '$upts' ORDER BY pts DESC LIMIT 1")
or die(mysql_error());
Then after getting the rank for the top 3 users , php will now add the ranks to each of the user(row) in that array(of course , add it to the rank owner, not just simply place it in).
Then JSON encode it out.
How can i do this?
I am not sure if this is what you want. That is combine the two query into one query. Please take a look at http://sqlfiddle.com/#!2/ad419/8
SELECT user.username,user.pts,rank.rank
FROM user LEFT JOIN rank
ON user.pts <=rank.pts group by user.id
UPDATED:
For extracting top 3, could do as below;
SELECT user.username,user.pts,rank.rank
FROM user LEFT JOIN rank
ON user.pts <=rank.pts
GROUP BY user.id
ORDER BY pts DESC LIMIT 3
If i understand correctly, you need to get values from Rank and Users tables. In order to do that in just one query You need to add FK (Foreign Key) to the Rank table that points to a specific user in the Users table.
So you need to add userId to the Rank table and then you can run:
SELECT r.rank, u.points from users u,rank r where u.userId = r.userId
This is roughly what you need.
Not quite the answer to your exact question, but this might be of use to you: How to get rank using mysql query. And may even mean that you don't require a rank table. If this doesn't help, I'll check back later.
Use this query
$query = "SELECT
u.pts,
r.rank
FROM users as u
left join ranks as r
on r.pts = u .pts
ORDER BY pts DESC
LIMIT 3";
This will bring what you required without putting into an array
$rec = mysql_query($query);
$results = arrau();
while($row = mysql_fetch_row($rec)){
$results[] = $row;
}
echo json_encode($results);
It looks like what you're trying to do is retrieve the rank with the highest point requirement that the user actual meets, which isn't quite what everyone else is giving here. Fortunately it is easily possible to do this in a single query with a nice little trick:
SELECT
user.username,
SUBSTRING_INDEX(GROUP_CONCAT(rank.rank ORDER BY pts DESC),",",1) AS `rank`
FROM user
LEFT JOIN rank ON user.pts >= rank.pts
GROUP BY user.id
ORDER BY pts DESC
LIMIT 3
Basically what the second bit is doing is generating a list of all the ranks the user has achieved, ordering them by descending order of points and then selecting the first one.
If any of your rank names have commas in then there's another little tweak we need to add on, but I wouldn't have thought they would so I've left it out to keep things simple.