I can't figure out join..
need to select all rows from one table where a column equals something in another table..
like this:
SELECT ALL FROM someTable
WHERE COLUMN someColumn = '123' (IN A DIFFERENT TABLE)
something like that..
and the IDs need to match of course..
Just use an INNER JOIN:
SELECT *
FROM SomeTable S
JOIN SomeOtherTable S2
ON S.SomeKey = S2.SomeKey
WHERE S.SomeColumn = '123'
A Visual Explanation of SQL Joins
I wasn't completely clear of your question, so you may not need the WHERE clause if that represented your JOIN criteria.
A bit error in my question, let me clarify
tblplace
id place
1 London
2 Paris
3 New York
tbltraveller
tr_id tr_name id
1 John 3
2 Jackson 2
3 Susanna 1
4 Jimmy 3
5 Lucy 2
The problem is missing some data for New York:
Paris Jackson Lucy
New York
My code(guess there is an error in the while loop):
<?php
require_once("connMysql1.php");
$qry = "SELECT * FROM tblPlace WHERE tblPlace.id > 1 ORDER BY tblPlace.id";
$result = mysqli_query($db_link, $qry);
$qry1 = "SELECT tblPlace.id, tblPlace.Place, tbltraveller.tr_id,
tbltraveller.tr_name, tbltraveller.id FROM tblPlace INNER JOIN tbltraveller ON
tblPlace.id = tbltraveller.id WHERE tblPlace.id > 1 ORDER BY tbltraveller.id";
$result1 = mysqli_query($db_link, $qry1);
$no_of_row1 = mysqli_num_rows($result1);
$no_of_row = mysqli_num_rows($result);
echo "<table border=1 cellpadding=10>";
if ($no_of_row >0){
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td>";
echo $row['place']."<br>";
echo "</td>"." ";
echo "<td>";
while ($row1 = mysqli_fetch_assoc($result1)){
if($row1['id'] == $row['id']){
echo $row1['tr_name']." ";
}
}
echo "</td>";
"</tr>";
}
}
echo "</table>";
?>
`
Related
I have a 2 tables called forums and forum_categories in database
forum_categories
cat_id
forums
cat_id
I am trying to count the total for each category for some reason it displays total record for all records.
I have 2 categories so far in the database
first category has value of 1
second category has value of 2
In category one, I have two forums that has a cat_id of 1
In category two, I have one forum that has a cat_id of 2
it displays
category 1 -------------------- 3 ---------------
category 2 -------------------- 3 ---------------
when it should display
category 1 -------------------- 2 ---------------
category 2 -------------------- 1 ---------------
$topics_count always displays 3.
$sql = "SELECT * FROM forum_categories, forums WHERE forum_categories.cat_id = forums.cat_id GROUP BY forum_categories.cat_id";
$result = query($sql);
$sql2 = "SELECT fc.cat_title COUNT(f.forum_id) FROM forums as f LEFT JOIN forum_categories fc ON (f.cat_id = fc.cat_id) GROUP BY f.cat_id";
$result2 = query($sql2);
$topics_count = count($result2);
while (($row = mysqli_fetch_assoc($result)) != false) {
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
$forum_name = $row['forum_name'];
echo "<tr>";
echo "<td>$cat_id</td>";
echo "<td><a href='viewforum.php?f={$cat_id}'>$cat_title</a><br>$forum_name admin</td>";
echo "<td>$topics_count</td>";
echo "<td>0</td>";
echo "</tr>";
}
This bit of code below gives you all results:
$sql2 = "SELECT * FROM forums WHERE cat_id = cat_id";
$result2 = query($sql2);
$topics_count = row_count($result2); // here this would be 3*
*in case of 2 for cat1 + 1 for cat2 and you echo this in each table row as:
echo "<td>$topics_count</td>";
therefore you see the total number (3) on both rows.
What you are actually trying is to join forums and forum_categories table, get the forum_categories.cat_title and COUNT(forums.cat_id) while grouping the results by forums.cat_id
SELECT
fc.cat_title,
COUNT(f.forum_id)
FROM forums as f
LEFT JOIN forum_categories fc ON (f.cat_id = fc.cat_id)
GROUP BY f.cat_id
Here is the same demo fiddle I've sent you yesterday.
Your query would then return you something like:
Demo Forum 1 | 2
Demo Forum 2 | 1
UPDATE:
$sql2 = "SELECT
fc.cat_id,
fc.cat_title,
f.forum_name,
COUNT(f.forum_id) as count
FROM forums as f
LEFT JOIN forum_categories fc ON (f.cat_id = fc.cat_id)
GROUP BY f.cat_id";
$result2 = query($sql2);
while (($row = mysqli_fetch_assoc($result)) != false) {
$cat_id = $row['cat_id']; // category id
$cat_title = $row['cat_title']; // category title
$forum_name = $row['forum_name']; // forum name
$count = $row['count']; // count of forum_id (grouped by cat_id)
echo "<tr>";
echo "<td>$cat_id</td>";
echo "<td><a href='viewforum.php?f={$cat_id}'>$cat_title</a><br>$forum_name admin</td>";
echo "<td>$count</td>";
echo "<td>0</td>";
echo "</tr>";
}
Here, I'm pretty sure the count would be okay, but not sure about "Forum Name".
try this
replace this
while (($row = mysqli_fetch_assoc($result)) != false) {
with this
while ($row = mysqli_fetch_assoc($result)) {
the below is my mysql table structure, the values inside are not fixed and can get changed by admin.
town_name | product_name| pending_quantity
------------------------------------------
Jaipur | Mobile | 5
Jaipur | Charger | 3
Surat | wallet | 2
Surat | Mobile | 1
Surat | battery | 3
Surat | cover | 2
In my php code, i stored all these values in 3 different arrays (one for each column) and everything is fine. I want to show this data in HTML table but the structure it needs to be shown is a problem to me. Below is the expected HTML table structure.
town_name | Mobile | charger | wallet | Battery | cover
-------------------------------------------------------
Jaipur | 5 | 3 | | |
Surat | 1 | | 2 | 3 | 2
So far, I've achieved to show rows and column headers the way it should be. But am now unable to put the pending quantity values in its place.
This is my php code if its of any help
<tbody>
<?php
$count = 1;
$row=0;
foreach($townid as $townKey=>$townValue) {
echo "<tr>";
echo "<td>$count</td>";
echo "<td>$townValue</td>";
foreach($items as $productKey=>$productValue) {
echo "<td>$pendingqty[$townKey]</td>";
$row++;
}
$row++;
echo "</tr>";
$count++;
}
?>
</tbody>
The column headers (mobile, charger etc etc) are dynamic and the town names are also dynamic. Please help me in achieving the desired result via mysql or html.
PHP code that gets values inside arrays
$townid2 = array();
$itemname = array();
$pendingqty = array();
$items = array();
$query = mysql_query("select o.town_id as townid, od.item_name as itemname, sum(od.pending_qnty) as pendingqty FROM tbl_order o JOIN tbl_order_data od on o.id = od.order_id where month(o.order_date)='1' GROUP BY o.town_id, od.item_name ");
while($row = mysql_fetch_array($query)) {
$townid2[]=$row['townid'];
$pendingqty[] = $row['pendingqty'];
$items[] = $row['itemname'];
}
$townid = array_unique($townid2, SORT_REGULAR);
$query2 = mysql_query("select od.item_name FROM tbl_order_data od JOIN tbl_order o on o.id=od.order_id where od.order_id IN (select id from tbl_order where month(order_date)='1') group by od.item_name order by o.item_name ");
$productArray = array();
while($row2 = mysql_fetch_array($query2)) {
$productArray[] = $row2['item_name'];
}
Here is how I would do it (I'm using mysql_query because you did, but it's deprecated so you really should switch):
$things = array();
$columns = array('Mobile','charger','wallet','Battery','cover'); //this can/should be populated dynamically using a distinct product query, but I'm hard-coding it because I'm lazy
$query = mysql_query("select o.town_id as townid, od.item_name as itemname, sum(od.pending_qnty) as pendingqty FROM tbl_order o JOIN tbl_order_data od on o.id = od.order_id where month(o.order_date)='1' GROUP BY o.town_id, od.item_name");
while($row = mysql_fetch_array($query)) {
$things[$row['townid']][$row['itemname']] = $row['pendingqty'];
}
... //whatever code until you're ready for the table
echo "<table><thead><tr>";
foreach($columns as $column){
echo "<th>".$column."</th>";
}
echo "</tr><thead><tbody>";
foreach($things as $key=>$value){
echo "<tr><td>".$key."</td>";
foreach($columns as $column){
echo "<td>".(isset($value[$column]) ? $value[$column] : null)."</td>";
}
echo "</tr>";
}
echo"</tbody></table>";
Here's my take
$itemnames = array();
$pendingqtys = array();
$query = mysql_query("SELECT
od.item_name AS itemname
FROM
tbl_order o
JOIN
tbl_order_data od ON o.id = od.order_id
WHERE
MONTH(o.order_date) = '1'
GROUP BY o.town_id");
while($row = mysql_fetch_array($query)) {
$itemnames[] = $row['itemname'];
}
$query = null;
$query = mysql_query("SELECT
o.town_id AS townid,
od.item_name AS itemname,
SUM(od.pending_qnty) AS pendingqty
FROM
tbl_order o
JOIN
tbl_order_data od ON o.id = od.order_id
WHERE
MONTH(o.order_date) = '1'
GROUP BY o.town_id , od.item_name");
while($row = mysql_fetch_array($query)){
$pendingqtys[$row['townid']][$row['itemname']]=$row['pendingqty'];
}
Then to display the results
echo "<table><thead><tr><th>Town Names</th>";
foreach($itemnames as $itemname){
echo "<th>".$itemname."</th>";
}
echo "</tr></thead><tbody>";
foreach ($pendingqtys as $town => $pendingqty){
echo "<tr><th>".$town."</th>";
foreach ($itemnames as $itemname){
echo "<td>".$pendingqty[$itemname]."</td>";
}
echo "</tr>";
}
echo "</tbody></table>";
i have such a table:
r_id date recipe_name
1 2012-05-20 Cheese Bread
1 2012-05-21 Cheese pie
2 2012-05-20 Spanish Bread
I would like to get all the data under r_id 1 to be in a single row how can i do that using Sql.I need to achieve something like this:
r_id recipe_name
1 Cheese Bread,Cheese pie
2 Spanish Bread
how can i do this using php too?
Use GROUP_CONCAT
SELECT r_id, GROUP_CONCAT(recipe_name)
FROM yourTable
GROUP BY r_id
Here's the php version
$query = "SELECT id, recipe_name FROM myTable";
$rs = mysqli_query($query);
$results = array();
while($r = mysqli_fetch_assoc($rs)) {
$results[$r['id']][] = $r['recipe_name'];
//$results[$r['id']][] = "<a href=''>".$r['recipe_name']."</a>";
}
foreach($results as $id => $recipes) {
print $id . ' ' . implode(',', $recipes) . "<br>";
}
I have 3 mysql tables. I want to display leaderboard for team in descending order of d_money for particular day (like day 1, day 2, day 3.)
user(u_id(p),name)
team(t_id(p),u_id(f),t_name,t_money,days_money) and
history(t_id(f),day,d_money).
First i collected all t_id's in $tid_arr. Then for each t_id, i wrote query to get t_name and its days money.(for particular day. Here - day 1). It displays the result. But i want the result sorted (descending order of d_money). But i couldn't find the soultion.
$query = $con->prepare("SELECT t_id FROM team");
$query->execute();
$tid_arr = $query->fetchAll();
echo "<table border='1'>";
foreach($tid_arr as $tid)
{
$que = $con->prepare("SELECT d_money, t_name FROM team, history WHERE history.t_id=$tid['t_id'] AND team.t_id=history.t_id` AND history.day='1'");
$que->execute();
while($info = $que->fetch(PDO::FETCH_NUM))
{
echo "<tr>";
echo "<td>".$info[0]."</td>";
echo "<td>".$info[1]."</td>";
echo "</tr>";
}
}
echo "</table>";
If you want to order by d_money then t_id, you can use the following query. The 1st query is unnecessary and should be removed.
SELECT d_money, t_name FROM team a
LEFT JOIN history b ON a.t_id=b.t_id
WHERE history.day='1'
ORDER BY d_money DESC, t_id DESC
p.s. user table is not used ?
Add a Join and Order By clause to your SQL statement to be
echo "<table border='1'>";
$que = $con->prepare("SELECT T.t_id, H.d_money, T.t_name
FROM team T INNER JOIN history H ON T.t_id=H.t_id
WHERE H.day='1'
ORDER BY d_money DESC");
$que->execute();
while ($info = $que->fetch(PDO::FETCH_NUM)) {
echo "<tr>";
echo "<td>".$info[0]."</td>";
echo "<td>".$info[1]."</td>";
echo "</tr>";
}
echo "</table>";
question table
========================
question_id
1
2
3
4
user_answer table
========================
user_id question_id
33 2
44 4
33 1
44 3
This code will return the question id (2 and 1)
what I want is to retrieve the other question id from table question so I want
the result to be (3 and 4)
$fadi = mysql_query("SELECT * FROM question
LEFT OUTER JOIN user_answer
ON user_answer.question_id = question.question_id
WHERE user_answer.user_id = 33");
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array($fadi))
{ Print "<tr>";
Print "<th>question </th> <td>".$info['question_id'] . "</td></tr>";
} Print "</table>"; }
I believe what you are looking for are the words IS NULL:
$fadi = mysql_query("SELECT * FROM question
LEFT OUTER JOIN user_answer
ON user_answer.question_id = question.question_id
AND user_answer.user_id = 33
WHERE user_answer.question_id IS NULL");
You can go one step further by only retrieving the question ID from the question table:
$fadi = mysql_query("SELECT question.question_id FROM question
LEFT OUTER JOIN user_answer
ON user_answer.question_id = question.question_id
AND user_answer.user_id = 33
WHERE user_answer.question_id IS NULL");
Edit: Improved version.
$fadi = mysql_query("SELECT * FROM question WHERE question.question_id NOT IN (SELECT user_answer.question_id FROM user_answer WHERE user_answer.user_id = 33)");
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array($fadi))
{ Print "<tr>";
Print "<th>question </th> <td>".$info['question_id'] . "</td></tr>";
} Print "</table>"; }
MySQLi version:
$link = mysqli_connect($hostname, $username, $password, $database);
if (!$link){
echo('Unable to connect to database');
}
else{
$fadi = mysqli_query("SELECT * FROM question WHERE question.question_id NOT IN (SELECT user_answer.question_id FROM user_answer WHERE user_answer.user_id = 33)", $link);
Print "<table border cellpadding=3>";
while($info = mysqli_fetch_array($fadi,MYSQL_BOTH))
{ Print "<tr>";
Print "<th>question </th> <td>".$info['question_id'] . "</td></tr>";
} Print "</table>"; }
}
mysqli_close($link);
See in action: http://www.sqlfiddle.com/#!2/27b6f/21
What could be an answer is to take the same mysql_query you used
then from mysql_fetch_array retrieve the 'question_id' values and finally, if you have the count of the questions (if not you can use mysql count), to use php function array_diff() to retrieve (from the incremental sorted array of integer values of question_id or from the array of question_id values from 'question' table) exactly what you want