Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL -- How to do this better?

Tags:

sql

php

mysql

$activeQuery = mysql_query("SELECT count(`status`) AS `active` FROM `assignments` WHERE `user` = $user_id AND `status` = 0");
$active = mysql_fetch_assoc($activeQuery);

$failedQuery = mysql_query("SELECT count(`status`) AS `failed` FROM `assignments` WHERE `user` = $user_id AND `status` = 1");
$failed = mysql_fetch_assoc($failedQuery);

$completedQuery = mysql_query("SELECT count(`status`) AS `completed` FROM `assignments` WHERE `user` = $user_id AND `status` = 2");
$completed = mysql_fetch_assoc($completedQuery);

There has to be a better way to do that, right? I don't know how much I need to elaborate as you can see what I'm trying to do, but is there any way to do all of that in one query? I need to be able to output the active, failed, and completed assignments, preferably in one query.

like image 854
Andrew Avatar asked Apr 22 '10 16:04

Andrew


People also ask

How can I make MySQL query run faster?

Adjust the size and properties of the memory areas that MySQL uses for caching. With efficient use of the InnoDB buffer pool, MyISAM key cache, and the MySQL query cache, repeated queries run faster because the results are retrieved from memory the second and subsequent times.

What is MySQL Optimization?

Optimization involves configuring, tuning, and measuring performance, at several levels. Depending on your job role (developer, DBA, or a combination of both), you might optimize at the level of individual SQL statements, entire applications, a single database server, or multiple networked database servers.


1 Answers

You can try something like this query

SELECT Status , COUNT(*) StatusCount 
FROM assignments
WHERE Status IN (0, 1, 2)
AND User = $user_id 
GROUP BY Status
like image 94
Adriaan Stander Avatar answered Oct 17 '22 01:10

Adriaan Stander