MySQL JOIN and MAX - php

Hi I've got a query which does what I want to by displaying reviews which are rated first then followed by reviews which have yet to be rated. However I can't seem to get it to order correctly.
What the result should look like:
5
4
0
0
...
At the moment it is doing this:
4
5
0
0
...
Here is my query
$sql = $db->query( "
SELECT branch.*, MAX(review.rating) AS m
FROM branch
LEFT OUTER JOIN review ON branch.bid = review.bid
WHERE branch.address2 LIKE '$query' OR branch.postcode LIKE '$query-%'
GROUP BY branch.bid
ORDER BY m DESC, branch.branch ASC
LIMIT $start,$limit
" ) or die( "Select failed: (" . $db->errno . ") " . $db->error );

Sub-query solution by Meghraj Choudhary should work.
However, Joins are faster. Sub-queries require additional disk accessing. Assuming branch.bid is a primary key the following should be faster:
SELECT b1.*, b2.m FROM branch b1
INNER JOIN
(
SELECT branch.bid, MAX(review.rating) AS m
FROM branch
LEFT OUTER JOIN review ON branch.bid = review.bid
WHERE branch.address2 LIKE '$query' OR branch.postcode LIKE '$query-%'
GROUP BY branch.bid
LIMIT $start,$limit
) b2 ON
b1.bid = b2.bid
ORDER BY b2.m DESC, b1.branch ASC
I have not tried this. So, please try it and post back.

Related

Mysql query error limit

I write a website and use php. When ı write
$cat = mysql_query("
Select m.Image_link AS link
, m.Name
, m.ID
, c.Name AS catName
from movie m
join has_category mc
on m.ID = mc.movie_id
join category c
on c.ID = mc.category_id
where c.Name = '$category'
ORDER
BY ID desc"
);
this query everything is okay but when ı insert limit, ı take error.
#$sayfa=$_GET['s'];
$kacar=12;
$toplansayfa=ceil(mysql_num_rows($cat)/$kacar);
$baslangic=($sayfa * $kacar) - $kacar;
$bul_cat=mysql_query("
Select m.Image_link AS link
, m.Name
, m.ID
, c.Name AS catName
from movie m
join has_category Mc
on m.ID = mc.movie_id
join category c
on c.ID = mc.category_id
where c.Name = '$category'
ORDER
BY ID desc
limit $baslangic, $kacar
");
echo mysql_error();->
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-12, 12' at line 1
Where is my mistake..thanks for your interest.
As with many SQL programming errors, it helps a great deal to look at the actual text of the query you tried to run.
So, try this:
$query = "Select movie.Image_link AS link, movie.Name, movie.ID, category.Name AS catName from (movie inner join has_category on movie.ID=has_category.movie_id inner join category on category.ID=has_category.category_id) where category.Name='$category' ORDER BY ID desc limit $baslangic, $kacar";
$bul_cat = mysql_query($query); /*deprecated API! */
if (!$bul_cat) {
echo "query failed: " . $query;
echo mysql_error(); /* deprecated API! */
}
You will almost certainly spot the problem right away when you display the actual query you tried to run. I'm sure Paul Siegel's diagnosis is correct... your query says LIMIT -12,12. You Can't Do That™.

Average and comparative left join MySQL

I'm trying to fetch information from 2 different MySQL tables.
The primary table is this one:
From this one I use the information to get the average rate from this:
How can I write an SQL query that will get me the average rating by counting all the rows with rating_house = house_id, and sort it by highest rating and if equal ratings, the one with the most rates.
This is what I have come up with myself:
$sql = "SELECT l.location_address, "
. "r.rating_structure+r.rating_inventory+r.rating_service/3 AS average "
. "FROM houses h "
. "LEFT JOIN rating r ON h.house_id = r.rating_house "
. "LEFT JOIN location l ON h.house_address = l.location_id "
. "WHERE h.house_deleted IS NULL SORT BY average DESC LIMIT 10";
$result = $db_connect->prepare($sql);
if($result->execute()){
while($user_data = $result->fetch(PDO::FETCH_ASSOC)){
$user_data['location_address']."<br>";
}
}
However I get no output?
For performance use INNER JOINs instead of LEFT JOINs if you know that the related rows must exist.
SELECT l.location_address,
(SUM(r.rating_structure)+SUM(r.rating_inventory)+SUM(r.rating_service))/3 AS average
FROM houses h
INNER JOIN rating r ON h.house_id = r.rating_house
INNER JOIN location l ON h.house_address = l.location_id
WHERE h.house_deleted IS NULL
GROUP BY l.location_address
ORDER BY 2,
(SUM(r.rating_structure)+SUM(r.rating_inventory)+SUM(r.rating_service)) DESC
LIMIT 10
Below query should return houses sorted by average ratings:
select h.house_id, (sum(hr.rating_structure) + sum(rating_inventory) + sum(rating_service))/3 as "average"
from house h left outer join house_rating hr on h.house_id = hr.rating_house
group by h.house_id
order by average

How to combine two Post/Category tables MYSQL SELECT queries into one

I have two MySQL queries:
1) "SELECT ID,post_title,post_category,post_perma FROM ".TBL_POSTS."
WHERE published='1' AND page='0' ORDER BY ID DESC LIMIT 10"
2) "SELECT p.cat_ID,p.cat_nicename FROM ".TBL_CATEGORIES." n, ".TBL_CATEGORIES." p
WHERE n.lft BETWEEN p.lft AND p.rgt AND n.cat_ID='".post_category."' ORDER BY p.lft
First query selects posts and then second select the Path of the category by post_category please note that post_category will be taken from first query means post_category is common in both table.. in first table it is named as post_category and in second it is cat_ID
Right now I am running it in foreach loop which is not good. Also one thing to be noticed that second query will also return Array and that one array should correspond to post_category
Can any SQL expert help me?
Many Thanx
Please try this it might be helpful to you.
SELECT a.ID, a.post_title,a.post_category,a.post_perma, b.cat_ID, b.cat_nickname
FROM (SELECT ID,post_title,post_category,post_perma FROM ".TBL_POSTS." WHERE published='1' AND page='0' ORDER BY ID DESC LIMIT 10) a
LEFT JOIN (SELECT p.cat_ID as cat_ID,p.cat_nicename as cat_nickname FROM " . TBL_CATEGORIES . " n, " . TBL_CATEGORIES . " p WHERE n.lft BETWEEN p.lft AND p.rgt AND n.cat_ID = '" .$post_category. "' ORDER BY p.lft) b ON a.ID = b.cat_ID
I would use LEFT JOIN
Like this:
$sql = "SELECT `p`.`ID`,`p`.`post_title`,`p`.`post_category`,`p`.`post_perma`,`c`.`cat_ID`,`c`.`cat_nicename` FROM `".TBL_POSTS."` AS `p` ";
$sql .= "LEFT JOIN `".TBL_CATEGORIES."` AS `c` ON `c`.`cat_ID`=`p`.`post_category` WHERE `p`.`published`='1' AND `p`.`page`='0' ORDER BY `p`.`ID` DESC LIMIT 10";
You may need to tweak the WHERE clause to suite your needs more..
Please Note: This is one string, i have just split them onto two lines so it is easier to read. .= is to append the current string.

How to use LIKE for mysql search with JOIN and ORDER BY the count of most rows/votes in the vote table?

I have three tables I need to use in a search, Movies, Reviews, and Votes. I want to use the LIKE function for Movie.Title and Review.Subject and order them by the amount of the most votes for each match.
In the Votes table there is a ReviewID, UserID, IsGood. Every time a user votes, an insert is done with the MovieID, UserID, and 1 or 0 for the IsGood, 1 meaning good 0 meaning bad.
So one review may have 0 good and bad votes, or 5 good and 3 bad, etc. I would like to show the results in the following order:
Review 1 - 10Good / 3Bad
Review 2 - 4Good / 3Bad
Review 3 - 0Good / 0Bad
The matches with the most good votes at top, the ones with the most bad votes at the bottom.
This is the mysql query I wrote up and is obviously wrong, but hoping someone can help me out:
mysql_query("
SELECT m.Title, r.Subject, v.ReviewID FROM Movies m
LEFT JOIN Reviews r
ON m.ID=r.MovieID
INNER JOIN Votes v
ON r.ID=v.ReviewID
WHERE (m.Title LIKE '%" . $search . "%'
OR r.Subject LIKE '%" . $search . "%')
ORDER BY MAX(COUNT(v.IsGood='1')) LIMIT 10")or die(mysql_error());
Here is a fuller answer.
To get the sum or good votes and bad votes from a set of joined table rows, you need to group the like rows together.
Below should give you the desired result.
mysql_query("
SELECT m.Title, r.Subject, v.TipID, sum(v.IsGood) as IsGood, sum(v.isBad) as isBad FROM Movies m
LEFT JOIN Reviews r
ON m.ID=r.MovieID
LEFT JOIN Votes v
ON r.ID=v.ReviewID
WHERE (m.Title LIKE '%" . $search . "%'
OR r.Subject LIKE '%" . $search . "%')
GROUP BY m.Title, r.Subject, v.TipID
ORDER BY sum(v.IsGood) desc, sum(v.isBad) asc LIMIT 10")or die(mysql_error());

GROUP BY not working

$sSql = "SELECT COUNT(DISTINCT `tsu`.`id`) AS `count`
FROM `" . $this->_sPrefix . "users` AS `tsu`
INNER JOIN `" . $this->_sPrefix . "entries` AS `tse`
ON `tsu`.`id`=`tse`.`subscriber_id`
AND `tse`.`subscriber_type`='" . BX_DOL_SBS_TYPE_VISITOR . "'
WHERE 1
GROUP BY `tsu`.`id`
LIMIT 1";
Instead of counting the entries, it only returns 1. If I remove the group BY clause then it works. How can I fix the GROUP BY to make it work better?
The WHERE 1 does nothing, so it can be removed.
The GROUP BY can also be removed since you are not grouping by anything, your COUNT DISTINCT is on the whole table, no?
As Orbling points out, the LIMIT 1 can be removed too because COUNT DISTINCT returns only one value by definition.
Does it do what you want then?
You are grouping by tsu.id.
Each individual tsu.id group will by definition only have 1 distinct tsu.id in the group what do you expect it to return?
SELECT u.id, COUNT(e.id)
FROM users AS u
INNER JOIN entries AS e ON e.subscriber_id = u.id
WHERE e.subscriber_type = 'BX_DOL_SBS_TYPE_VISITOR'
GROUP BY u.id

Categories