Sorting count in multiple tables - php

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;

Related

How can I order query by another table?

I have a long query, but I keep it simplified:
$query = $this->db->query(" SELECT id FROM oc_products ORDER BY ...? ");
Here is the problem. In this table I have all the products, but I have a second table, oc_seller_products, where I have same column ID, which match with oc_products.
I want to be ordered first id's which dont appear in oc_seller_products, and at last, appear id's which appear in oc_seller_products.
For example: in oc_products I have ID: 1,2,3,4,5
In oc_seller_products I have only ID: 4
I need to be ordered like this: 5,3,2,1 and the last: 4
I have a marketplace, so I want first my products to appear, on category page, then my sellers products.
I really have no idea how to do that.
select op.id
from oc_products op
left join oc_seller_products osp using (id)
order by osp.id is null desc, op.id desc
osp.id is null will be 1 when there is not an oc_seller_products record and 0 when there is, so sort by that, descending, first. And then after that, within those two categories, you seem to want descending id order.

How do you fetch records from a table with order of another table using foreign key

I have two tables in my SQL, 'post' and 'business'
The columns in the post are:
Post_ID
Content
Img
Business_ID
The columns in business are
Business_ID
Business name
Business rating
What I want is I want the posts which are posted by businesses with high business rating come first before others, please is there a way to fetch the posts with order of business rating???
To order results of posts with associated business rating you need a join query
select p.*
from posts as p
join business as b on b.business_id = p.business_id
order by b.business_rating desc
To arrange the ratting use order by query
select * from posts,business order by business_rating where posts.business_ID=business.business_ID;

php mysql inner join - get a particular row

This is my query to get model information from one table and a single picture from another table. What changes do I have to make to this query in order for it to get the picture where ORDER BY sort DESC? In the table of the pictures, there is a field by the name "sort". The default value for the field for each row is 0. But one random row has the value of 1. I want to get that particular row. I don't, however, want to use WHERE sort=1 because then even in the case where no row has the sort value 1, one row should still get fetched.
$sql="SELECT tc.id,tc.alias,tc.firstname,tci.imagename
FROM ".$pre."models tc
INNER JOIN ".$pre."model_images tci ON tc.id=tci.userid
WHERE activated=1 AND sex=$sex AND city=$city AND published=1
GROUP BY tc.id ORDER BY firstname ASC";
Thank you in advance!
Solved using:
SELECT tc.id,tc.alias,tc.firstname,
(SELECT imagename FROM ".$pre."model_images WHERE userid= tc.id
ORDER BY sort DESC LIMIT 1) AS imagename
FROM ".$pre."models tc
WHERE tc.activated=1 AND tc.sex=1 AND tc.city=2 AND tc.published=1
ORDER BY tc.firstname ASC
You should place that in your WHERE clause aswell. One t hing to note though is to be carefull with the way you're using the column names. It's better to tell to which table they belong.
So this:
WHERE activated=1 AND sex=$sex AND city=$city AND published=1
Should be:
WHERE tc.activated=1 AND tc.sex=$sex AND tc.city=$city AND tc.published=1
And then simply add the 'sort' column to it:
WHERE tc.activated=1 AND tc.sex=$sex AND tc.city=$city AND tc.published=1 AND tci.sort=1
If no results are returned, then make sure that there are records that meet the required conditions. Because there's nothing wrong with the query. Try to print your query to the screen etc. to see if every variables has a value.
edit:
You should lose the GROUP BY.
SELECT tc.id,tc.alias,tc.firstname,tci.imagename
FROM ".$pre."models tc
INNER JOIN ".$pre."model_images tci ON tc.id=tci.userid
WHERE tc.activated=1 AND tc.sex=$sex AND tc.city=$city AND tc.published=1 AND tci.sort=1

sorting by value in another table php mysql

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

Searching multiple tables in query

SELECT DISTINCT business.name AS businessname
,business.description AS description
FROM business
, category
, sub_categories
WHERE business.cityID = '$city'
AND (category.name LIKE '%$name%'
OR sub_categories.name LIKE '%$name%')
AND business.status = 0
Pls the above SQL code is suppose to search a set of two tables the ones in the bracket and return the result, but for some reason, it's not doing so. What am i doing wrong?
Thank You.
Your query would produce a cartesian product. Depending on the size of your tables that could take a considerable amount of time.
Based on your clarification I'd use a subquery to check for matching categories, this way you don't have to use distinct in your query as it would only return each business once. I also suggest you to start with a decent SQL tutorial.
SELECT name AS businessname
,description AS description
FROM business
WHERE cityID = '$city'
AND status = 0
AND ( categoryID in (select id from category where name like '%$name%')
or subcategoryID in (select id from sub_categories where name like '%$name%')
)
Two things come to mind:
You are not joining any of the three tables together. Consider adding a few LEFT JOIN clauses.
You are selecting columns from only one table. If you wanted columns from other tables, you should add them to your SELECT clause.

Categories