Mysql how to use SUM and COUNT in the same query - php

I have the query below, which is supposed to get all the "record" fields from a mysql table called users. The record field's values must be bigger than 0 for it to count. and the query only returns true if 3 or more records found (where record > 0)
The query below makes sense to me, but its returning the following PHP error : Operand should contain 2 column(s)
$query = "
SELECT * FROM users u
WHERE (
SELECT COUNT(record) AS record,
SUM(CASE WHEN record > 0 THEN 1 ELSE 0 END)
FROM users
) >= 3
";
Can SUM and COUNT not be used in the same query? I've used them simultaneously in the past with no problems.
Any help would be great thank
EDIT ---------------------
Table : users
--------------
id value
--------------
1 1
2 1
3 1
4 0
5 0
6 -1
7 -10
8 0
I'd like to only return a result if the value field in the table above is bigger than 0. But I also only want to return a result if the total number of values found in the table (where value > 0) are 3 or more.

You can just use the count function to count, a where to limit the data, and the having function to check that you have the number of records you want.
select count(*) as counted
from users
where record > 0
having counted > 3
Demo: http://sqlfiddle.com/#!9/29ed41e/1
With the above query your PHP will have the results as the first index, or counted depending on how you fetch. You don't need to loop the fetch because there will only be 1 row returned.
Roughly:
$row = $query->fetch();
return $row['counted'];
The number of rows will be 1 so you don't want to count the number of rows, you want the actual returned value.

Related

Incrementing random cell in SQL with shared value

I want to select the lowest value in the 'n' sql column and increment it by 1. If the lowest value is present in multible rows, then I want to choose among those rows at random. For instance, in the example table below where the lowest number is 0 I want to randomly choose between the rows where ID = 1, 2, or 3.
ID
n
1
0
2
0
3
0
4
1
5
2
The code below will increment all three rows where n = 0. How do I randomly select just 1? I use Adminer as database.
$sql = "UPDATE studycondition SET n=n +1 WHERE n=(SELECT MIN(n) FROM studycondition)";
use
"UPDATE studycondition SET n=n +1 WHERE n=(SELECT MIN(n) FROM studycondition) limit 1"
Add limit in your inner query and update by id
UPDATE studycondition SET n = n + 1
WHERE id=(SELECT id FROM studycondition order by n asc limit 1)

how to count values from a table and return true, only if the value is found 5 times using php mysql

I am building a user like system using PHP and MySQL.
THIS IS MY TABLE
--------------
ID value
---------------
1 1
2 0
3 1
4 1
5 1
6 0
I'm trying to write a mysql query in php, that only displays total value count, if the total value count is greater than 5. i.e only return the query as true if there are more than 5 records found in the table.
Can someone please help me? I've tried many things.
This is my code i have tried so far
$query = " SELECT COUNT(value) AS value,
CASE
WHEN value > 0 THEN value ELSE 0 END
FROM users
";
$query = $this->db->query($query);
$query->result_array();
if ($query->num_rows() > 0){
echo "more than 5 records are found";
}
THANKS
(EDIT - To make the question clearer)
So if we look at the table below (TABLE 1), value = 1 is found 6 times in the table. So the query should return true. This is because I am trying to count all values, where value = 1, and not value = 0. And I only want to return the query, if value = 1 is found 5 times or more.
TABLE 1
--------------
ID value
--------------
1 1
2 0
3 1
4 1
5 1
6 0
7 1
8 1
If we look at TABLE 2 below, value = 1 is only found 2 times in that table. So we return the query as false, because we need value = 1 to be found in the table more than 5 times to return true.
TABLE 2
--------------
ID value
--------------
1 1
2 0
3 1
4 0
5 0
6 0
7 0
8 0
I'd like to make this happen in the query and not using if statements outside the query using php. ie, if($results > 5) { return true}
THANKS
Hope this will help you :
You can use count_all to get the count and then get user records
$count = $this->db->count_all('users');
if ($count > 5)
{
$query = $this->db->get('users');
$records = $query->result_array();
print_r($records);
}
You could use following query to get data if there are 5 or more than 5 records exists
select *
from users u
where (
select count(*)
from users
) >= 5
Demo
Here is another demo if table has less than 5 rows
if you want to get the sum of values in the column value you can use this.
$data = $this->db->get('users')->result_array();
foreach ($data as $row) {
$num_value[] = $row['value'];
}
$num_value = array_sum($num_value);
if($num_value > 5){
echo 'value is more than 5';
}
else{
echo 'value is equal or less than 5';
}

mysql total and difference for multiple rows

I'm new to mysql. I'm trying to write a query to calculate the total and difference for multiple rows, and then put them in specific columns.
Eg. I want to sum all Entity'A' of Type'1' then subtract from the result, the sum of Entity'A' of type'0'. While simultaneously populating a table to show where this difference is positive or negative.
Sample table:
Entity Type Value
A 1 200
B 1 500
C 0 350
B 0 150
C 1 100
A 1 50
A 1 350
Expected Output:
Entity Diff-Positive Diff-Negative
A 600
B 350
C 250
Note that Entity'A' for example may not have an entry for Type'0'
This is basically aggregation. You need a conditional to split the values into separate columns. One way uses greatest():
select entity,
greatest(sum(case when type = 1 then value else - value end), 0) as diff_positive,
greatest(sum(case when type = 0 then value else - value end), 0) as diff_positive
from t
group by entity;

mysql second priority where clause

So for example I have a table users, with a column 'count' and a column 'uid' which is the primary key.
uid | count
1 | 20
2 | 20
3 | 20
4 | 20
4 | 18
I want to select exactly one row which has count less than or equal to the present row. For example, I have the row where uid = 2.
Now I want to select a column which has count less than or equal to the present count value which is "20". and I want to select exactly one row which is closest to it.
Now I will have the choice to select either the row which has uid = 3 or uid = 4. In such case, I will want to select the column with the lowest uid value such that it is greater than the present uid value which is 2. Therefore I will want uid = 3 as my result.
How to put this in a mysql query ?
So something like this?
SELECT * FROM users
WHERE count <= 20
ORDER BY count DESC, uid ASC
LIMIT 1
That'll sort the results so that everything above 20 is discarded, and you get the rest in decreasing count order, with lower user ids taking priority if there are multiples of the same count. The LIMIT 1 restricts the query to return only one row.
If you want to make the comparison to an existing row, your easiest bet is to do this:
SELECT * FROM users
WHERE count <= 20
AND uid != 2
ORDER BY count DESC, uid ASC
LIMIT 1
SELECT * FROM users
WHERE count <= 20
AND uid IN (3,4)
ORDER BY uid ASC,count DESC
LIMIT 1

PHP - SQL: fetching results in round robin fashion

I have a table, which consists of 3 fields:
id
name
status
Every time I get the results, it should give me 5 names whose status = 1.
Suppose the db contains following:
id name status
1 A 1
2 B 1
3 C 0
4 D 1
5 E 0
6 F 0
7 H 1
8 I 1
9 J 1
10 K 1
11 L 1
12 M 0
1st time, fetch should return: A,B,D,H,I (5 records)
2nd time, fetch should return: J,K,L,A,B (5 records)
UPDATE: I don't want typical pagenation. Consider I have 12 available names from A1 to A12. The first fetch should return A1-A5, second fetch A6-A10 and third fetch A11, A12, A1, A2, A3. So when I reach the end, I need to get records starting from the first to fill the 5 slots.
i am doing it in php with mysql
This looks like some sort of job allocation script?
You need 2 things:
the highest ID returned last time the script was run (lastID)
a number larger than the maximum ID in the table (bigNum)
Then you can write your query as
SELECT
id, name
FROM
table
WHERE
status=1
ORDER BY
(bignum + id) MOD (bigNum + lastID + 1)
LIMIT 5
Shazaam!
Keep track of the ids of the records returned, and for the following queries do:
select top 5 *
from (
select top 5 *
from MyTable
where status = 1
and id not in (1,2,4,7,8)
order by name
union
select top 5 *
from MyTable
where status = 1
order by name
) a
$q = mysql_query("SELECT name FROM table WHERE status = 1 LIMIT 5);
while ($row = mysql_fetch_row($q))
{
.... //first 5
}
$q = mysql_query("SELECT name FROM table WHERE status = 1 LIMIT 5,5);
while ($row = mysql_fetch_row($q))
{
.... //second 5
}
this uses the offset functionality of mysql- think of it as pagination for your results.

Categories