Query and table - MAX and Join - php

Still very new to all of this so bear with me.
Have 3 tables
table 1: member
Mem_index, Mem_name
1 joe
2 Mark
Table 2: Course
Course_index, Course_Name
1 Math
2 Reading
Table 3 : data
Data index,Member,Course,Score
1 1 1 85
2 1 2 75
3 2 1 95
4 1 2 65
SO what I would like to do is create a table:
Do a query and gather all of the courses, find the max score for each course and attribute the member name to it.
Table result should look like:
Course, Max score,name
Math 95 Mark
Reading 75 Mark
I can do the query individually but unsure of how to loop it and then propogate the data into the table.

How about this query for SQL?
SELECT c.course_name, MAX( d.score ), m.mem_name
FROM members m
JOIN data d on m.mem_id = d.member
JOIN course c on c.course_id = d.course
GROUP BY d.course
ORDER BY d.score, m.mem_name, c.course_name
Not sure if the field names match up but you get the idea - tested this in sql with some dummy data.
Data
Index Member Course Score
1 1 1 60
1 1 1 85
Course
course_id course_name
1 Math
2 English
3 Science
Members
mem_id mem_name
1 Mark
2 James
You will get the following
Course Name Score Member
Math 85 Mark

Try this query :
SELECT c.course_Name , MAX(d.score),m.mem_name
FROM data d
JOIN course c ON d.course=c.course_index
JOIN members m ON m.mem_index = d.member
GROUP BY d.course
ORDER by MAX(d.score) DESC

Related

How to get data from different tables in MySQL database and display in a table with php

I have read many topics but none have given me exactly what i need
I have 3 tables
products
id
product_name
1
Heineken
2
Budweiser
transaction
id
user_id
date
amount
32
4
01/23/2023
10000
45
2
01/23/2023
20000
57
4
01/23/2023
5000
transaction_details
id
transaction_id
product_id
1
32
1
2
32
2
3
45
2
4
45
1
5
57
1
Now how can i achieve this
SELECT FROM transaction WHERE user_id = 4 then use the results to SELECT FROM transaction_details and display it in a table using a single sql query
And when displaying the results from transaction_details i want to use product_name
This is the result i want
transaction_id
products_id and name
32
1. Heineken
32
2. Budweiser
57
1. Heineken
I have tried to select from transaction table where id is equal to 4 and i got two results, i don't know what to do next
Using Mysqli Join Query with select concat option in in your select query
Please Using This Way
select tran.id,CONCAT(pro.id,'.',pro.product_name) as products_id_and_name from transaction as tran join transaction_details as trand on tran.id = trand.transaction_id JOIN products as pro on pro.id = trand.product_id WHERE tran.user_id = 4;

Assign Text (Label) to values in SQL Query Result

All data in my tables are in numeric format. For example,
class sex subject medium
5 1 1 1
1 1 1 2
4 3 3 1
5 1 3 2
1 1 3 1
3 1 2 2
1 2 2 2
Other Table contains Description to each value for each table. For Example,
Table Column value text
Student class 1 1ST
Student class 2 2ND
Student class 3 3RD
Student class 4 4TH
Student class 5 5TH
Student sex 1 male
Student sex 2 female
Student sex 3 creator
Student medium 1 English
Student medium 2 Hindi
I am trying to provide a text (label to each column when user queries). I have been able to do it for one column. For example,
SELECT class, sex, avg(total_marks) as total
FROM (
SELECT value, text as sex
FROM Label
WHERE table_name = 'Student' and
Column = 'class' or
) AS Label INNER JOIN Student on value = class
GROUP BY class, sex
This results in
class sex total
1ST 1 64.80
1ST 2 59.66
2ND 1 78.96
2ND 2 96.97
3RD 1 52.67
3RD 2 81.77
4TH 1 61.99
4TH 2 99.78
5TH 1 72.90
5TH 2 70.59
Instead of 1 / 2 /3 in sex I want to show male, female and creator. Select and Group by columns can be more than 4 at times. I am using MySql and PHP Laravel to do this.
I guess I found the answer. Any suggestions are most welcome.
SELECT T1.class, T2.sex, SUM(weight)
FROM household_characteristics
INNER JOIN (SELECT value_label_name as code, value_label_value FROM labels
WHERE table_name = 'Student' and columns = 'class' ) AS T1 ON T1.code = Student.class
INNER JOIN (SELECT value_label_name as code, value_label_value FROM labels
WHERE table_name = 'Student' and columns = 'sex' ) AS T2 ON T2.code = Student.sex
GROUP BY class, sex

count number of rows associated with their id in another table

Hi We have 3 Table of a music which is something like this in MySql :
1st Table :
the first table is for playlist table where music playlist is exist.
playlistId playlistTitle categoryId
1 hello 0
2 wow 0
3 wi-fi 0
4 awesome 0
5 sixer 1
6 four 1
7 boundary 2
2nd Table :
2nd table is for songRelation table where every playlist is associated with thier song
playlistId songId
1 4
1 3
1 43
1 57
1 98
2 56
2 67
2 90
2 78
3 98
3 78
3 89
43 90
3rd Table : the 3rd table is for song table where song detail exist
songId songTitle
4 hello
3 real hero
43 singalone
57 awesom
98 really
78 sakaka
98 shikwa
89 moha
90 hello2
67 Sneh
actually i am fetching the result something like this:
playlistId songId categoryId songTitle
1 4 0 hello
1 3 0 real hero
2 56 0 singalone
2 67 0 Sneh
3 78 0 sakaka
3 98 0 Shikwa
where the every playlistId will be with their first 2songIdand with theircategoryIdand also withsongTitle`.
but i want to count the total song with every playlistId
after getting the total song result i want will be something like this :
playlistId songId categoryId songTitle totalSong
1 4 0 hello 5
1 3 0 real hero 5
2 56 0 singalone 4
2 67 0 Sneh 4
3 78 0 sakaka 3
3 98 0 Shikwa 3
here is the jsfiddle Demo where query is without totalSong http://sqlfiddle.com/#!9/7eda7/5
What subquery will be added to get the above desired result.
To get exactly the result you asked, use this:
select p.playlistId,
s.songId,
p.categoryId,
s.songTitle,
(select count(*) from songRelation where playlistId = p.playlistId) totalSong
from playlist p
inner join songRelation r on p.playlistId = r.playlistId
inner join song s on r.songId = s.songId
Using a group by on the main query would merge the detailed song data, forcing you to run two queries: one for details (first 4 fields) and a second query, to recover the totals (last column). Using this solution, you get all detailed data and totals, the sub-query will recover the count of songs for each playlist, the way you asked.
UPDATE:
This way, suggested by rlanvin, should make the query faster, because instead on computing the subquery for each row, it gets computed only once, and then is joined to the main query. The result is the same:
select p.playlistId,
s.songId,
p.categoryId,
s.songTitle,
r1.totalSong
from playlist p
inner join songRelation r on p.playlistId = r.playlistId
inner join song s on r.songId = s.songId
inner join (SELECT playlistid, COUNT(songId) as totalSong from songRelation group by playlistid) r1 on p.playlistId = r1.playlistId
I have added this query to ur SQLFIDDLE.
SELECT p.playlistId, s.songId, p.categoryId, s.songTitle,
(select count(sr1.songId) from songRelation sr1
where sr1.playlistid=p.playlistid
group by sr1.playlistId) as total,
#r := IF (#pid = p.playlistId,
IF (#pid := p.playlistId, #r+1, #r+1),
IF (#pid := p.playlistId, 1, 1)) AS rn
FROM playlist AS p
CROSS JOIN (SELECT #r:=0, #pid:=0) AS vars
INNER JOIN songRelation AS sr ON p.playlistId = sr.playlistId
INNER JOIN song AS s ON sr.songid = s.songid
ORDER BY p.playlistId, s.songId ) AS t
WHERE t.rn <= 2
It is giving the required output. Check the Demo Here
Using Group Functions you can do this:
SELECT `playlistid`, COUNT(`songid`)
FROM `playlist`
GROUP BY `playlistid`

mysql join and sum problems

Im having some trouble with this.
Here's an example of my tables.
Booking
id zone_id name excursion_id
1 2 1
2 1 1
3 2 1
The table where I have the quantities
booking_price
id_booking id_price quantity
1 1 2
1 2 3
2 1 1
2 2 0
3 1 2
3 2 3
Here the zone table
Zone
id Name
1 a
2 b
3 c
So I want to have a table like that
Zone_id Quantity
1 1
2 10
3 0
The problem is when im joining tables and filtering by excursion_id im not getting ALL the zones.
I want to know how many people goes in each zone.
I think better way of doing it is
select z.id, coalesce(sum(bp.quantity),0) as quantity
from Booking b
right join Zone z on z.id = b.zone_id AND b.excursion_id = 1
left join booking_price bp on bp.id_booking = b.id
group by z.id
demo http://sqlfiddle.com/#!2/771f5/13
You could use a query like:
SELECT zone.id as zone_id,
sum(quantity) as Quantity
FROM zone
LEFT JOIN Booking on Booking.zone_id = zone.id
LEFT JOIN Excursion on Excursion.id_booking = Booking.id
GROUP BY zone.id

Help with limiting a joined mysql database query

I have written a query which returns all records with some many-to-many joins correctly for the entire set or an individual article using WHERE a.id = ?
SELECT a.id, date_added, title, content, category_id, person_id, organization_id, c.name AS category_name, firstname, lastname, o.name AS organization_name
FROM articles AS a
LEFT OUTER JOIN articles_categories AS ac ON a.id=ac.article_id
LEFT OUTER JOIN categories AS c ON c.id=ac.category_id
LEFT OUTER JOIN articles_people AS ap ON a.id=ap.article_id
LEFT OUTER JOIN people AS p ON p.id=ap.person_id
LEFT OUTER JOIN articles_organizations AS ao ON a.id=ao.article_id
LEFT OUTER JOIN organizations AS o ON o.id=ao.organization_id
ORDER BY date_added
BUT!
I've hit a brick wall trying to work out how to limit the articles to a specific number of IDs, for working with pagination.
I'm ideally trying to use as simple and clear SQL statements as possible because I'm using the codeigniter framework with their active record class.
http://codeigniter.com/user_guide/database/active_record.html
Would really appreciate some help as I don't want to revert to using multiple queries for this as I've tried to reduce it down to a single query for database efficiency.
Have search around and tried some alternatives but nothing seems to work. Many thanks!
For example the results I return are like this
---------------------------------------------------------------------
id title category_id person_id organization_id
---------------------------------------------------------------------
1 test 1 1 1
1 test 2 1 1
1 test 1 2 1
1 test 1 1 2
1 test 5 1 1
1 test 8 1 1
1 test 1 4 1
1 test 1 4 2
1 test 1 1 1
2 test 2 2 1 1
2 test 2 1 2 1
2 test 2 1 1 2
2 test 2 5 1 1
2 test 2 8 1 1
2 test 2 1 4 1
2 test 2 1 4 2
I need the results like this so that I can create sub-arrays in the php like this:
$articles = $query->result_array();
$output = array();
foreach ($articles as $article) {
// set up article details
$article_id = $article['id'];
// add article details
$output[$article_id]['article_id'] = $article_id;
$output[$article_id]['date_added'] = $article['date_added'];
$output[$article_id]['title'] = $article['title'];
$output[$article_id]['content'] = $article['content'];
// set up people details and add people array with details if exists
if (isset($article['person_id'])) {
$person_id = $article['person_id'];
$output[$article_id]['people'][$person_id]['person_id'] = $person_id;
$output[$article_id]['people'][$person_id]['lastname'] = $article['lastname'];
$output[$article_id]['people'][$person_id]['firstname'] = $article['firstname'];
}
// set up organizations details and add organizations array with details if exists
if (isset($article['organization_id'])) {
$organization_id = $article['organization_id'];
$output[$article_id]['organizations'][$organization_id]['organization_id'] = $organization_id;
$output[$article_id]['organizations'][$organization_id]['organization_name'] = $article['organization_name'];
}
// set up categories details and add categories array with details if exists
if (isset($article['category_id'])) {
$category_id = $article['category_id'];
$output[$article_id]['categories'][$category_id]['category_id'] = $category_id;
$output[$article_id]['categories'][$category_id]['category_name'] = $article['category_name'];
}
}
But if I just use LIMIT (with offset etc) 1
the results I get are
---------------------------------------------------------------------
id title category_id person_id organization_id
---------------------------------------------------------------------
1 test 1 1 1
instead of
---------------------------------------------------------------------
id title category_id person_id organization_id
---------------------------------------------------------------------
1 test 1 1 1
1 test 2 1 1
1 test 1 2 1
1 test 1 1 2
1 test 5 1 1
1 test 8 1 1
1 test 1 4 1
1 test 1 4 2
1 test 1 1 1
which is my desired result.
OK, so finally I worked out how it is possible.
Thought i'd include it here in case anyone else has the same problem.
Changing this line
FROM articles AS a
to this
FROM (SELECT * FROM articles LIMIT 5,3) AS a
does what I wanted.
So, why don't you use OFFSET 0,10 and LIMIT *number_of_results* in the SQL Query? (if I understood the question)
Specific number of IDs... WHERE ID IN (2,4,6,8)... ?
Are you using codeigniter's pagination?
http://codeigniter.com/user_guide/libraries/pagination.html
You can easily limit the number of records that are being returned using the MySQL LIMIT clause. This can be achieved like the following with your sample query.
SELECT a.id, date_added, title, content, category_id, person_id, organization_id, c.name AS category_name, firstname, lastname, o.name AS organization_name
FROM articles AS a
LEFT OUTER JOIN articles_categories AS ac ON a.id=ac.article_id LEFT OUTER JOIN categories AS c ON c.id=ac.category_id
LEFT OUTER JOIN articles_people AS ap ON a.id=ap.article_id LEFT OUTER JOIN people AS p ON p.id=ap.person_id
LEFT OUTER JOIN articles_organizations AS ao ON a.id=ao.article_id LEFT OUTER JOIN organizations AS o ON o.id=ao.organization_id
ORDER BY date_added
LIMIT 10
Where 10 is the number of records you wish to display. The MySQL LIMIT clause allows you to specify a limit of the number of records and an initial offset. Like so:
LIMIT <offset>,<limit>
In your case <offset> would be the current page * the number of records on a page. <limit> would be the number of records you would like to display per page.

Categories