I've currently got a table with users and variable user status (1, 2, 3, 4, 5 etc). I am currently calculating the number of users in each status separately
$query = "SELECT COUNT(*) FROM users WHERE status = 1";
$result = $pdo->query($query);
$users1 = $result->fetchColumn();
$query = "SELECT COUNT(*) FROM users WHERE status = 2";
$result = $pdo->query($query);
$users2 = $result->fetchColumn();
etc
I could get a fetch, then loop through all the results and add each status but I was wondering if there is a better way to do it with a query?
You can use group by and get the list with the count
SELECT status, COUNT(*) as my_count FROM users group by status;
NB with this you can't use fetchColumn .. but fetchRow .and access by key
you jsut need to add status as group by
SELECT COUNT(*),status FROM users group by status
Related
My review_shared table looks like this. The column names are review_shared_id, cat_id, review_id, user_id, contact_id.
I'm trying to figure out a way of seeing if $cat_id is shared by users other than the current user, $user_id, who in this case is 10219.
For example $cat_id is 188. Is this shared with users other than 10219? Yes - it's shared with user_id number 3729.
I'm not sure how to proceed, would be grateful for some help.
What I have so far is:
//check if $cat_id is being used by users other than $user_id
//we do this in the review_shared table
$query3 = "SELECT * FROM review_shared WHERE cat_id = ?";
$stmt3 = $con->prepare($query3) or die(mysqli_error($con));
$stmt3->bind_param('i', $cat_id) or die ("MySQLi-stmt binding failed ".$stmt3->error);
$stmt3->execute() or die ("MySQLi-stmt execute failed ".$stmt3->error);
$result3 = $stmt3->get_result();
while ($row = $result3->fetch_assoc()) {
//get the corresponding user_id for that cat_id
$matching_user_id = $row["user_id"];
If ($cat_id is shared by users other than the current user, $user_id) {
}
else {
}
Just add it to the where clause using a not equal operator (<> or != will both work in MySQL).
The query below will return all distinct userids. I added distinct, because it seems that there are multiple rows for cat 188 and the same userid, so without distinct, you would get that same user id multiple times. This query will return 0 rows if there are no other users that this cat is shared with.
SELECT DISTINCT
user_id
FROM review_shared
WHERE cat_id = ?
AND user_id <> ?
If you just want to know how many, you can count it. The query below will return one row with one value. That value is the number of users it is shared with apart from the given user id. The query will return the value 0 if there are no such users. distinct is added within the count, to count each distinct user_id only once. Otherwise your example data would result in 4, because cat 188 is shared 4 times with the same user.
SELECT
COUNT(DISTINCT user_id) AS user_count
FROM review_shared
WHERE cat_id = ?
AND user_id <> ?
how would i go about ordering by a value that is not in the table where i am selecting from, in this instance the value $count1 is not in the table search.
count has the same identifying id as that of the thing it is being reffered to in the other table, this is where count1 is grabbed
$q = $db->prepare("SELECT COUNT(rating) FROM ratings WHERE id='$id' AND rating = 'd'");
$q->execute();
$count1 = $q->fetchColumn();
$query = "SELECT * FROM search WHERE title LIKE '$each' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();
that is from ratings, how would i go about ordering the entries like that, so that they are based off the number of count1 and are decided, i might have to implement something like
$query = "SELECT * FROM search WHERE title LIKE '$each' AND id = '$id' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();
Possible Duplicate: Mysql order by specific ID values
Same thing here, you'll just output your $count1as a comma separated string and add it in the SQL query as ORDER BY FIELD(COUNT,___comma_sep_string___)
ratings is a table, not a database. You can join tables or use subqueries to get the desired result, without having to make multiple queries.
You haven't described how the FOREIGN_KEY is set up in the ratings table, but assuming you have something ratings.search_id, this should work:
SELECT search.*, (SELECT COUNT(rating)
FROM ratings
WHERE ratings.search_id = search.id
AND rating = 'd'
) AS rating_count
FROM search
WHERE title LIKE '$each'
ORDER BY rating_count
I want to count the results in my table... but I am usually confronted with a decision, what column do I select? Should I select the primary key? Wild Card? What has the most performance? Does it matter? Below is an example of how I call it
// Wild Card, I feel like this is the worst one for performance?
$query = "SELECT * FROM table WHERE status = ?";
// Only selecting one column? Is there a better way
$query = "SELECT id FROM table WHERE status = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i',$status);
$stmt->execute();
$stmt->store_result();
$returned_amount = $stmt->num_rows;
$stmt->free_result();
$stmt->close();
Well, if you want MySQL to handle the count, you can just do the following
$query = "SELECT COUNT(*) as count FROM `table` WHERE `field` = ?";
The as count part means that you can access the count as if it were a column.
You should SELECT COUNT(`id`) FROM `table` WHERE `status`=?, much more efficient ;)
If you are willing to count all the results of your query (ie: for pagination), you can use FOUND_ROWS() option:
In your main query you need to add SQL_CALC_FOUND_ROWS option just after SELECT and in second query you need to use FOUND_ROWS() function to get total number of rows.
SELECT SQL_CALC_FOUND_ROWS id FROM table WHERE status = 'something' LIMIT 10;
SELECT FOUND_ROWS();
More info in dev.mysql.com
I want to fetch the total count of records in MySQL db table and also use the limit with this. For example, there are 100 rows and the limit I want to use let suppose is 10. I know how to do this using two queries but I want to do this in one go.
SELECT count(*) as total_rows FROM mytable; // gets the total count of rows
SELECT col1,col2 FROM mytable LIMIT 0, 10; // gets the 10 rows of col1,col2
I want to do this in one go. Any idea.
Thanks.
Here is the SQL Fiddle that demonstrates how the below works:
SELECT m.*,
(
SELECT COUNT(*)
FROM mytable AS sm
) AS TotalCount
FROM (
SELECT mt.col1, mt.col2
FROM mytable AS mt
LIMIT 0, 10
) AS m
Have a look at Shayan Husaini's answer on How to get the total row count with MySQLi
I have updated his original answer after trying it out myself. You have to add "SQL_CALC_FOUND_ROWS" after SELECT in your query and add a second query as shown in the code snippet below.
$sql1 = "SELECT SQL_CALC_FOUND_ROWS col1,col2 FROM mytable LIMIT 0, 10";
$sql2 = "SELECT FOUND_ROWS()";
$result1 = $conn->query($sql1);
$result2 = $conn->query($sql2);
$TotalRcount = $result2->fetch_row();
// I have added this next line to correct the answer
$TotalNumRows = $TotalRcount[0];
You can use $result1 to access your results as you normally would.
I have a SQL Query, although it is executing, but how should i verify if it is giving me the desired result.
For example: My query
$query3 = "SELECT COUNT(DISTINCT(uid)) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'";
In the above query i am trying to count the number of distinct user ID's(uid) from the table named user-infowhere date is 2011-10-10.
How should i display the count which is calculated for the given date?.I need to know it and perform some further operations on it!
$query3 = "SELECT COUNT(DISTINCT uid) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'";
$result = mysql_query($query3);
$row = mysql_fetch_array($result);
echo $row['num'];
Just do:
SELECT COUNT(DISTINCT uid) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'
This SO post goes into some details about how count and count(distinct ...) work. With just count, there is a hidden/assumed function of count(all ... ) actually happening (it's just the default value). If you want to only count distinct things, switch it to the non-default and do the count(distinct ...) instead. I didn't know it existed for my first 6 months of writing sql or so...
You can set a variable sing the result...
SET #userVar=SELECT
COUNT(DISTINCT uid)
FROM
user_info
WHERE
DATE(starttime)='2011-10-10';
Then you can use that variable in your next operation or query.