MySQL order by $variable - mysql

I am trying to think of a way to order the results from the highest number to the lowest one.
The problem here is that those numbers will be from a different table and I am not sure how I should do it.
Please check out below.. *
Thanks!
*Edit:
I know that I suck at coding but still :)
What I need is instead of ORDER BY id to be Order by $results (highest number to lower)
Current Code I am using:
$query = "SELECT * FROM tablea WHERE id > 1 AND status = '1' ORDER BY id ASC;";
$result = #mysql_query($query);
for ($i=0; $i < #mysql_num_rows ($result); $i++) {
$row = #mysql_fetch_array($result);
$total = $total + 1;
$results = '';
$noinv = '';
$query2 = "SELECT SUM(number) FROM tableb WHERE id = '$row[id]' AND cur = '1' AND type = '1' AND pos = '1';";
$result2 = #mysql_query($query2);
$row2 = #mysql_fetch_array($result2);
if ($row2['SUM(number)'] == '') {
$row2['SUM(number)'] = '0.00';
}
$query3 = "SELECT SUM(number) FROM tableb WHERE id = '$row[id]' AND cur = '1' AND type = '1' AND pos = '2';";
$result3 = #mysql_query($query3);
$row3 = #mysql_fetch_array($result3);
if ($row3['SUM(number)'] == '') {
$row3['SUM(number)'] = '0.00';
}
$results = $row3['SUM(number)'] - $row2['SUM(number)'];
print $row['id'].' '.$row['status'].' '.$results;
}

your question is unclear, but try to give you general answer
select A.column1,A.column2,A.column3,count(B.*) total
from table A, table B
where A.Id=B.Id
group by A.Id
order by total desc

Related

Comparing two queries while executing

$query=mysql_query("SELECTcom_jobcard.job_card_num,process.process_name,employee.emp_name,employee.emp_code ,SUM(worked_qty) FROMcom_jobcard
INNER JOIN timer_completed ON timer_completed.job_card_id = com_jobcard.id
INNER JOIN process ON process.id = timer_completed.process_id
INNER JOIN employee ON employee.id = timer_completed.employee_id
AND job_card_id = ( SELECT id FROM com_jobcard WHERE job_card_num = 'JCID-1271742')
GROUP BY process.process_name,employee.emp_name ");
$query1 = mysql_query("SELECT com_jobcard.job_card_num,process.process_name,employee.emp_name,employee.emp_code,SUM(qc.rework_qty),qc.report_date,qc.id FROM qc
INNER JOIN com_jobcard ON qc.job_card_id = com_jobcard.id
INNER JOIN process ON process.id = qc.process_id
INNER JOIN qc_employees ON qc_employees.qc_id = qc.id
INNER JOIN employee ON employee.id = qc_employees.employee_id
AND qc_employees.qc_id = (SELECT qc.id
FROM qc
INNER JOIN com_jobcard ON qc.job_card_id = com_jobcard.id
AND com_jobcard.job_card_num = 'JCID-1271742')
GROUP BY process.process_name,employee.emp_name");
while ($row = mysql_fetch_array($query)) {
$row1 = mysql_fetch_array($query1);
if( ($row[1] == $row1[1]) && ($row[3] == $row1[3] ))
{
echo $row1[0] .$row1[1] .$row1[2] .$row1[3] .$row1[4];
}
}
Dear friends I am executing 2 queries simultaneously but I would like to compare both the result sets when $row[1] == $row1[1]) && ($row[3] == $row1[3] the condition is satisfied then it has to return the result but as if now it returns nothing could any one suggest me how to compare the result set of both the queries , Instead of using IF I have also used While statement , though I didn't recieve the result .
Please help me!
Thank you!
Use it like this
$row1 = mysql_fetch_array($query1);
while ($row = mysql_fetch_array($query)) {
while($row1) {
if( ($row['process_name'] == $row1['process_name']) && ($row['emp_name'] == $row1['emp_name'] ))
{
echo $row1['job_card_num'] .$row1['process_name'] .$row1['emp_name'] .$row1['emp_code'] .$row1['sum_qty'];
}
}
}
Because you have used $row[1] $row1[1] which has no value.
I ahev used alias vakue for SUM(qc.rework_qty) in your query as sum_qty

PHP - How to group from multiple sql queries

I got
for($i = $start_date;$start_date <= $end_date;$i->modify('+1 day')) {
$i->format('Y-m-d').'<br />';
$dates = $i->format('Y-m-d');
echo $query = "
SELECT md.dish_id
, md.daydate
, d.id
, d.dish_name
, d.weight
, d.price
FROM dishes d
LEFT
JOIN menu_details md
ON d.id = md.dish_id
WHERE md.daydate = '$dates'
";
$result = mysql_query($query);
}
while($row = mysql_fetch_array($result)) {
echo 'Date: '.$row['daydate'].'Name: '.$row['dish_name'].'<br />';
}
how can i row 'dish_name' for every date on a new row.In the database there are more then 1 row with same date=
You should try to avoid running queries in loops...
Try:
$query = "SELECT md.dish_id, md.daydate, d.id, d.dish_name, d.weight, d.price
FROM dishes d
LEFT JOIN menu_details md ON (d.id = md.dish_id)
WHERE md.daydate BETWEEN '$start_date' AND '$end_date'
GROUP BY md.daydate ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo 'Date: '.$row['daydate'].'Name: '.$row['dish_name'].'<br />';
}
What is the group by for? I think it may cause you to lose some of the results...

SELECT column/s based on boolean value

I have a left join select statement that I want to select specific columns based on the value of a variable that has either a '0' or a '1'. I thought I could implement this using CASE, but I don't seem to be having any luck.
If $variable contains a '0' I want my select statement to retrieve only users.user, table2.total1 and table2.total2, but if the $variable contains a '1' I want to select only users.user and table2.total.
$value = '1';
$conn->query(
"select users.user, table2.total, table2.total1, table2.total2
FROM users
LEFT JOIN table2 on users.user = table2.total AND $table2.date = CURDATE()
WHERE users.user = 'marketing' OR users.user = 'sales'
");
Does anyone have any ideas? Thanks.
You don't need to do this with sql, if in fact the query differ only by the select clause you could use a conditional and a variable:
$value = '1';
if($variable == '1') {
$select = "select users.user, table2.total1, table2.total2 ";
}
else {
$select = "select users.user, table2.total ";
}
$conn->query(
$select . "
FROM users
LEFT JOIN table2 on users.user = table2.total AND $table2.date = CURDATE()
WHERE users.user = 'marketing' OR users.user = 'sales'
");

Add many-to-many select into existing query

I have a query set up to return comments given from one user to another.
Now we want to allow the ability to rate these comments.
I've added a new table that has 3 fields: comment_id, user_id, and score.
How can I grab an array of {user_id,score} for any comment fetched?
Will I need to loop through the comments after they are fetched and run a second query? This approach could result in adding several extra queries.
Can it be done with a single query?
Here's the function I have now:
function getAllComments($args) {
if(empty($_SESSION['user']['id'])) return false;
$limit = 5;
if(isset($args['limit'])) $limit = $args['limit'];
$page = 1;
if(isset($args['page'])) $page = $args['page'];
$data = array();
$offset = ($page-1)*$limit;
$sql = "SELECT c.*,CONCAT(u1.firstName,' ',u1.lastName) AS owner,u1.title AS ownerTitle,CONCAT_WS(' ',u2.firstName,u2.lastName) AS senderName,u2.title AS senderTitle,a.name AS actionName,a.behavior
FROM comment AS c
JOIN user AS u1 ON c.recipient = u1.id
JOIN user AS u2 ON c.sender = u2.id
JOIN action AS a ON c.action = a.id
WHERE c.type=1";
if(isset($args['location'])) $sql .= " AND u1.location=?";
$sql .= " ORDER BY date DESC";
$sql .= " LIMIT ?";
$sql .= " OFFSET ?";
try {
$db = DB::getInstance();
$stmt = $db->dbh->prepare($sql);
$n = 1;
//THESE MUST STAY IN THE SAME ORDER TO MATCH THE ? PLACEHOLDERS
if(isset($args['location'])) $stmt->bindValue(($n++), $args['location'], PDO::PARAM_INT);
$stmt->bindValue(($n++), $limit, PDO::PARAM_INT);
$stmt->bindValue(($n++), $offset, PDO::PARAM_INT);
$result = $stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$rows = array();
if($result !== false) {
while($row = $stmt->fetch()) {
$rows[] = $row;
}
$data['comments'] = $rows;
return $data;
}else {
logit('Query Failed');
return false;
}
}catch(PDOException $e) {
logit($e->getMessage());
return false;
}
}
If you for example wanted all {comment_id, user_id, score} associated with the comments of user 5, your query would involve an INNER JOIN and look something like:
SELECT s.comment_id, s.user_id, s.score FROM CommentScore s
INNER JOIN Comment c
ON c.comment_id = s.comment_id
WHERE c.user_id = 5

making SQL more efficiency by making two queries into one instead of having a loop

I have the following code and was wondering how I could simplify it into one MYSQL statement
$sql = "SELECT sesionID
FROM `juegos_sesiones`
WHERE `usuarioID` = ".$_SESSION['MM_UserID'];
$query = mysql_query($sql, $cnx) or die(mysql_error());
//$row_rsPaises = mysql_fetch_assoc($rsPaises);
$exercises = mysql_num_rows($query);
echo $exercises;
//find total points
while( $row = mysql_fetch_array($query)){
$sql2 = 'SELECT correct_answers FROM `juegos_sesiones_detalle` WHERE `sesionID` = '.$row['sesionID'];
$query2 = mysql_query($sql2, $cnx) or die(mysql_error());
$details2 = mysql_fetch_assoc($query2);
$counter = $counter + $details2['correct_answers'];
}
echo '<br />'.$counter;
SELECT sum(correct_answers) as total_correct_answers
FROM `juegos_sesiones_detalle` d
INNER JOIN `juegos_sesiones` s on s.`sesionID` = d.`sesionID`
WHERE `usuarioID` = $_SESSION['MM_UserID']
You can read about joins here
You can write single query by using INNER JOIN as:
SELECT correct_answers
FROM juegos_sesiones_detalle a
INNER JOIN juegos_sesiones b
ON a.sesionID = b.usuarioID;
Try this :
$sql = "SELECT correct_answers FROM `juegos_sesiones_detalle` jsd
JOIN `juegos_sesiones` js
ON jsd.sesionID = js.`sesionID`
WHERE js.usuarioID = ".$_SESSION['MM_UserID'];