sorting by value in another table php mysql - php

I have two tables, one called episodes, and one called score. The episode table has the following columns:
id | number | title | description | type
The score table has the following columns:
id | userId | showId | score
The idea is that users will rate a show. Each time a user rates a show, a new row is created in the score table (or updated if it exists already). When I list the shows, I average all the scores for that show ID and display it next to the show name.
What I need to be able to do is sort the shows based on their average rating. I've looked at joining the tables, but haven't really figured it out.
Thanks

To order the results, use and ORDER BY clause. You can order by generated columns, such as the result of an aggregate function like AVG.
SELECT e.title, AVG(s.score) AS avg_score
FROM episodes AS e
LEFT JOIN scores AS s ON e.id=s.showId
GROUP BY e.id
ORDER BY avg_score DESC;

You're right. You have to JOIN these tables, then use GROUP BY on the 'episodes' table's 'id' column. Then you'll be able to use AVG() function on 'the scores' tables's 'score' column.
SELECT AVG(scores.score) FROM episodes LEFT JOIN scores ON scores.showId = episodes.id GROUP BY episodes.id

SELECT episodes.*, AVG(score.score) as AverageRating FROM episodes
INNER JOIN score ON (episodes.id = score.showId)
GROUP BY episodes.id
ORDER BY AVG(score.score) DESC

Related

MYSQL: INSERT INTO while also doing INNER JOIN in the same query

I'm having trouble understanding how to write this MySQL query and a lot of the answers I've been able to find here don't seem to help a lot.
I have two tables with these rows:
units
-----------------
unit_id (INT)
unit_name(STRING)
surveys
-----------------
survey_id (INT)
parent_unit(INT)
I am trying to add a record to the surveys table. In my query, I know the unit_name of parent_unit but I need to find out what the unit_id is.
I have not worked with mysql in a while so I am having trouble creating an INNER JOIN that would replace unit_name with the corresponding unit_id.
This is what I have tried so far, but I think I am very far from the answer:
$unit_name = "unit1"
INSERT INTO surveys (parent_unit)
SELECT * FROM units
INNER JOIN units ON $unit_name=units.unit_name
VALUES ("unit name") //This should be an INT
The result of this query would be:
survey_id | parent_unit
----------+------------
0 | 0
As the unid_id for the `parent_unit "unit1" is 0, which we can see in the units table:
> SELECT * FROM units WHERE unit_name LIKE "unit1";
unit_id | unit_name
--------+----------
0 | unit1
I hope I explained myself enough to be understood.
So start simpler. First, what is the query to find a unit id, given the unit name, from units? As an elementary query:
SELECT unit_id
FROM units
WHERE unit_name LIKE "the_unit_name_you_have"
So then we look at what you actually want to do: you need to build a survey record, and you have a unit name. Rather than doing a full table join for every possible unit, let's just repeat that exact select, and just drop that into the table:
INSERT INTO surveys (parent_unit)
SELECT unit_id AS parent_unit
FROM units
WHERE unit_name LIKE "the_unit_name_you_have"
(Also note that that AS is entirely optional, but can make things easier to track as human being)
Based on your explanation seems you need
a join between a 'unit name' from units and a parent_id from sessions based on the relation between unit_id and parent_id
INSERT INTO surveys (parent_unit)
SELECT unit_id
FROM units u
INNER JOIN surveys s ON u.unit_name = 'unit name'
and u.id = s.parent_unit

GROUP_CONCAT with ordering and missing fields

I have a series of tables that I want to get rows returned from in the following format:
Student ID | Last Name | First Name | Quiz Scores
-------------------------------------------------
xxxxxxx | Snow | Jon | 0,0,0,0,0,0,0,0
There's 3 relevant tables (changing any existing DB structure is not an option):
person - table of all people in the organization
enrollment - table of student and faculty enrollment data
tilt.quiz - table of quiz scores, with each row storing an individual score
The tricky part of this is the Quiz Scores. A row for the quiz score only exists if the student has taken a the quiz. Each quiz row has a module, 1 - 8. So possible quiz data for a student could be (each of these being a separate row):
person_id | module | score
---------------------------
223355 | 1 | 100
223355 | 2 | 95
223355 | 4 | 80
223355 | 7 | 100
I need the quiz scores returned in proper order with 8 comma separated values, regardless if any or all of the quizzes are missing.
I currently have the following query:
SELECT
person.id,
first_name,
last_name,
GROUP_CONCAT(tilt.quiz.score) AS scores
FROM person
LEFT JOIN enrollment ON person.id = enrollment.person_id
LEFT JOIN tilt.quiz ON person.id = tilt.quiz.person_id
WHERE
enrollment.course_id = '$num' AND enrollment_status_id = 1
GROUP BY person.id
ORDER BY last_name
The problems with this are:
It does not order the quizzes by module
If any of the quizzes are missing it simply returns fewer values
So I need the GROUP_CONCAT scores to at least include commas for missing quiz values, and have them ordered correctly.
The one solution I considered was creating a temporary table of the quiz scores, but I'm not sure this is the most efficient method or exactly how to go about it.
EDIT: Another solution would be to execute a query to check for the existence of each quiz individually but this seems clunky (a total of 9 queries instead of 1); I was hoping there was a more elegant way.
How would this be accomplished?
There are some assumptions here about your data structure, but this should be pretty close to what you're after. Take a look at the documentation for GROUP_CONCAT and COALESCE.
SELECT `person`.`id`, `person`.`first_name`, `person`.`last_name`,
GROUP_CONCAT(
COALESCE(`tilt`.`quiz`.`score`, 'N/A')
ORDER BY `tilt`.`quiz`.`module_id`
) AS `scores`
FROM `person`
CROSS JOIN `modules`
LEFT JOIN `enrollment` USING (`person_id`)
LEFT JOIN `tilt`.`quiz` USING (`person_id`, `module_id`)
WHERE (`enrollment`.`course_id` = '$num')
AND (`enrollment`.`enrollment_status_id` = 1)
GROUP BY `person`.`id`
ORDER BY `person`.`last_name`
First thing to do is use the IFNULL() function on the score
Then, use ORDER BY inside the GROUP_CONCAT
Here is my proposed query
SELECT
person.id,
first_name,
last_name,
GROUP_CONCAT(IFNULL(tilt.quiz.score,0) ORDER BY tilt.quiz.module) AS scores
FROM person
LEFT JOIN enrollment ON person.id = enrollment.person_id
LEFT JOIN tilt.quiz ON person.id = tilt.quiz.person_id
WHERE
enrollment.course_id = '$num' AND enrollment_status_id = 1
GROUP BY person.id
ORDER BY last_name

Mysql group by fetch last row

SELECT * FROM conversation_1
LEFT JOIN conversation_2
ON conversation_1.c_id = conversation_2.c_id
LEFT JOIN user
ON conversation_2.user_id = user.user_id
LEFT JOIN message
ON conversation_1.c_id = message.c_id
WHERE conversation_1.user_id=1
GROUP BY message.c_id
conversation_1 conversation_2
c_id user_id c_id user_id
1 1 1 2
2 1 2 3
3 2
I have a message DB build in Mysql
I make 4 tables user, conversation_1, conversation_2, message
when user try to open his message box, it will fetch out all conversations(conversation_1)
than join to user conversation_2 and use conversation_2 to find out which user
than join to the message.
c_id user_id user_name message
1 2 Alex Hi user_1, this is user_2
2 3 John hi user_3, user_2 don't talk to me
it works fine, however I want to display the message from last row GROUP BY
currently it display the 1st row in this group.
ps.conversation_1.c_id is auto increment and the c_id will insert to conversation_2 who has join this conversation
select * from (SELECT * FROM conversation_1
LEFT JOIN conversation_2
ON conversation_1.c_id = conversation_2.c_id
LEFT JOIN user
ON conversation_2.user_id = user.user_id
LEFT JOIN message
ON conversation_1.c_id = message.c_id
WHERE conversation_1.user_id=1
order by conversation_1.c_id desc) finalData
GROUP BY message.c_id
Beware that, as documented under MySQL Extensions to GROUP BY:
MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. This means that the preceding query is legal in MySQL. You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. Sorting of the result set occurs after values have been chosen, and ORDER BY does not affect which values within each group the server chooses.
This is what is happening to select the message (and potentially other columns) in your existing query.
Instead, you want the groupwise maximum:
SELECT messages.* FROM messages NATURAL JOIN (
SELECT c_id, MAX(m_id) m_id FROM messages GROUP BY c_id
) t

Sorting count in multiple tables

I'm working on a PHP/mySQL table that shows data I've put into my database, and I'm trying to make it sortable. I have two tables in my database:
Table "restaurant" has columns: ID and name
Table "item" has columns: ID, name and restaurantID (restaurantID is set to use the IDs from the "restaurant" table)
What I want to do is sort the restaurants by the number of times their ID shows up in the item table. I'm sure there must be a simple way to do this, Just haven't been able to figure it out. Any help would be greatly appreciated!
Try this...
select r.name, count(i.ID)
from restaurant r
left join item i on i.restaurantID = r.ID
group by r.name
order by count(i.ID) desc
I believe you can do it by using a query like following;
SELECT restaurant.*, COUNT(items.id) AS item_id FROM restaurants, items WHERE restaurant.id = items.restaurant_id ORDER BY item_id ASC;
As you may know, sorting by multiple column is possible as well;
SELECT restaurant.*, COUNT(items.id) AS item_id FROM restaurants, items WHERE restaurant.id = items.restaurant_id ORDER BY item_id ASC, restaurant.`name` DESC;

Join two tables and get the latest date.

Im new to this form and hopefuly I can get some awesome help!
I got three tables
1 "companies"
ID
2 "log"
compid
datum (date)
3 "sales"
datumnow (datetime)
uppdaterad (datetime)
I want to compare log and sales and get the latest or the "newest" entry and display a ASC list of companies from table 1 with only one company for each row. (comparing datum, datumnow & uppdaterad and get the highest date value displayed on one row for each ID from companies)
#RESULT
Rover - 2012-01-15
Daniel - 2012-02-01
Damien - 2012-03-05
I´ve struggled with this for a few days now and can´t get a hold of the solution.
App. ANY help! thanx.
You can use GREATEST() to return the most recent date from those three columns. This assumes you have another column in sales that relates to the other tables. From the structure you show above, the relationship is unclear.
SELECT
companies.ID,
GREATEST(log.datum, sales.datumnow, sales.uppdatedad) AS mostrecent
FROM
companies LEFT JOIN log ON companies.ID = log.compid
/* Assumes sales also has a compid column. Will edit if new info is posted */
LEFT JOIN sales ON companies.ID = sales.compid
WHERE log.userid='$userID' AND sales.seller='$userID'
For only one row with the max date per company, use a MAX() aggregate with a GROUP BY:
SELECT
companies.ID,
MAX(GREATEST(log.datum, sales.datumnow, sales.uppdatedad)) AS mostrecent
FROM
companies LEFT JOIN log ON companies.ID = log.compid
/* Assumes sales also has a compid column. Will edit if new info is posted */
LEFT JOIN sales ON companies.ID = sales.compid
WHERE log.userid='$userID' AND sales.seller='$userID'
GROUP BY companies.ID

Categories