w3resource

MySQL join using group by

Join using group by

In this page we have discussed how to use MySQL JOIN using GROUP BY.

Example

Sample table : book_mast


Code :

SELECT bk1.book_name,bk1.pub_lang,bk1.book_price 
FROM  book_mast bk1
JOIN(SELECT pub_lang,MAX(book_price) AS  price          
FROM book_mast           
GROUP BY pub_lang) AS bk2          
ON bk1.pub_lang=bk2.pub_lang AND bk1.book_price=bk2.price;

Explanation

The above MySQL statement will find the book name for each language with highest price of book. A sub query have been used to get the result.

Output :

example join using group by

PHP script:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>example-php-mysql-bit_count()</title>
</head>
<body>
<?php
echo "<h2>A list of the highest priced books with respect to each language : </h2>";
echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
echo "<tr style='font-weight: bold;'>";
echo "<td width='250' align='center'>Name of the book</td><td width='200' align='center'>Language</td><td width='200' align='center'>Price</td>";
echo "</tr>";
include("../dbopen.php");
$result = mysql_query("SELECT bk1.book_name,bk1.pub_lang,bk1.book_price
FROM  book_mast bk1 
JOIN(
SELECT pub_lang,MAX(book_price) AS  price
FROM book_mast 
GROUP BY pub_lang) AS bk2
ON bk1.pub_lang=bk2.pub_lang AND bk1.book_price=bk2.price");
while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo "<td align='center' width='200'>" . $row['book_name'] . "</td>";
echo "<td align='center' width='200'>" . $row['pub_lang'] . "</td>";
echo "<td align='center' width='200'>" . $row['book_price'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>

View the example in browser



Follow us on Facebook and Twitter for latest update.