Maximum value in a column - php

Is there a more efficient way to do this? I want the maximum value of a column (int) in a given MySQL table using PHP.
$results = $conn->query("SELECT statement_id FROM statement ORDER BY statement_id DESC LIMIT 1");
$next_statment_id = $results->fetch_assoc();
$next_statment_id = $next_statment_id['statement_id'];
echo $next_statment_id;

MAX is an OK method too
SELECT MAX(statement_id) AS statementIdentity
FROM statement;
output produce something like this:-
+-------------------+
| statementIdentity |
+-------------------+
| 4 |
+-------------------+

Consider the following:
SELECT COUNT(*) FROM test;
+----------+
| COUNT(*) |
+----------+
| 10000000 |
+----------+
SELECT i FROM test ORDER BY i DESC LIMIT 1;
+----------+
| i |
+----------+
| 18482903 |
+----------+
1 row in set (0.00 sec)
SELECT MAX(i) FROM test;
+----------+
| MAX(i) |
+----------+
| 18482903 |
+----------+
1 row in set (0.00 sec)
See. Not much in it.

Related

Join table fields with different ID in PHP

How to join many fields with different ID's in only one?
I have this MySQL table:
--------------------------------
| *UDH* | *Text* |
--------------------------------
| 050003B90301 | Hi my name is A|
--------------------------------
| 050003B90302 | rmin and I wan |
--------------------------------
| 050003B90303 | t be your frien |
--------------------------------
The UDH field is different but I need join the text field to copy to other table, the result must to be like this:
______________________________________________________________
| UDH | Text |
--------------------------------------------------------------
| 1 | Hi my name is Armin and I want be your frien |
---------------------------------------------------------------
Do you know a PHP sentence or other method to make something like this?
Use GROUP_CONCAT(). Like this:
select '1' as UDH, group_concat(`Text` separator '') as `Text` from myTable;
If you need to order by the UDH column, you can do that within the group_concat() call like this:
select '1' as UDH, group_concat(`Text` order by UDH separator '') as `Text` from myTable;
I just validated this query with the following test code based on your example:
mysql> create table myTable (UDH varchar(32), `Text` text) engine=innodb;
Query OK, 0 rows affected (0.05 sec)
mysql> insert into myTable (UDH, `Text`) values ('050003B90301', 'Hi my name is A'), ('050003B90302', 'rmin and I wan'), ('050003B90303', 't be your frien');
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from myTable;
+--------------+-----------------+
| UDH | Text |
+--------------+-----------------+
| 050003B90301 | Hi my name is A |
| 050003B90302 | rmin and I wan |
| 050003B90303 | t be your frien |
+--------------+-----------------+
3 rows in set (0.00 sec)
mysql> select '1' as UDH, group_concat(`Text` order by UDH separator '') as `Text` from myTable;
+-----+----------------------------------------------+
| UDH | Text |
+-----+----------------------------------------------+
| 1 | Hi my name is Armin and I want be your frien |
+-----+----------------------------------------------+
1 row in set (0.01 sec)

Retrieve last 3 years of data with custom date

Here's my query:
mysql> select * from jobs where datediff(now(),str_to_date(last_modified,'%M %d,%Y'))>=1095;
I get 0 results
mysql> select max(last_modified) from jobs;
+--------------------+
| max(last_modified) |
+--------------------+
| 9/9/2013 |
+--------------------+
1 row in set (0.06 sec)
mysql>
It doesn't seem to be working to well and Im not sure why. I think it has to do with the original formatting of the last_modified column
UPDATE
mysql> select distinct(last_modified) from jobs where datediff(now(),str_to_date(last_modified,'%m/%d/%Y'))>=1095 limit 10;
+---------------+
| last_modified |
+---------------+
| 12/4/2003 |
| 12/5/2003 |
| 12/6/2003 |
| 12/8/2003 |
| 12/9/2003 |
| 12/10/2003 |
| 12/11/2003 |
| 12/12/2003 |
| 12/13/2003 |
| 12/14/2003 |
+---------------+
10 rows in set (0.00 sec)
mysql>
Use str_to_date(last_modified,'%m/%d/%Y') instead of str_to_date(last_modified,'%M %d,%Y')

SQL - if exists return always 1

$sql = "SELECT EXISTS (SELECT usernev AS juzernev, SUM(mbsent) AS summ FROM data WHERE datum > DATE_ADD(NOW(), INTERVAL -1 MONTH) AND usernev='csib')'";
I have this query on this table(data) - the first col. is the usernev:
| sajtos | 1323 | 411 | 193.225.249.2 | 10.8.0.10 | 3661 | 2015-03-19 17:25:37 | 87 |
| csib | 318 | 26 | 5.187.169.135 | 10.8.0.6 | 10849 | 2015-03-19 19:11:37 | 88 |
| csib | 5 | 1 | 5.187.169.135 | 10.8.0.6 | 1234 | 2015-03-19 22:50:23 | 89 |
| gyuri | 26 | 31 | 193.225.249.2 | 10.8.0.14 | 3001 | 2015-03-19 22:56:54 | 90 |
So the problem is when i use this query it is returns 1 -> So with this query with username csib there were good results. But when i change the usernev to another (which is not exists) it is also returns 1.
Am i doing something wrong or i cant do it with EXISTS?
An aggregation function with no group by always returns one row. And, a query that has one row satisfies exists.
As a general rule, I always use select 1 with exists. There is no need to select anything more:
SELECT EXISTS (SELECT 1
FROM data
WHERE datum > DATE_ADD(NOW(), INTERVAL -1 MONTH) AND
usernev = 'csib'
);
You can also write this query as:
SELECT COALESCE(MAX(1), 0)
FROM data
WHERE datum > DATE_ADD(NOW(), INTERVAL -1 MONTH) AND
usernev = 'csib';
With an index on data(usernev, datum), the two probably have similar performance. Otherwise, the first would have better performance. I just mention this version because it has an aggregation function, making use of the fact that an aggregation query with no group by always returns one row.
The reason is you are using aggregate function sum and this will always return one row weather or not if there is any data.
You may need to remove the aggregate function inside the exists
Here is a demo
mysql> select exists (select sum(amount) from paymentlog where idusers = 1 );
+----------------------------------------------------------------+
| exists (select sum(amount) from paymentlog where idusers = 1 ) |
+----------------------------------------------------------------+
| 1 |
+----------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> select exists (select sum(amount) from paymentlog where idusers = 1111111111 );
+-------------------------------------------------------------------------+
| exists (select sum(amount) from paymentlog where idusers = 1111111111 ) |
+-------------------------------------------------------------------------+
| 1 |
+-------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> select exists (select * from paymentlog where idusers = 1111111111 );
+---------------------------------------------------------------+
| exists (select * from paymentlog where idusers = 1111111111 ) |
+---------------------------------------------------------------+
| 0 |
+---------------------------------------------------------------+
1 row in set (0.00 sec)

Simple UPDATE SQL Query

I'm doing a work for a client but since I haven't been using PHP/MySQL for a while I forgot some simple things, hope you can help me out.
I have the following SQL table:
ID (non-null, autoincrement) | credit (int)
My query should put the whole "credit" column to 0 except for the row that has the higher ID.
So I would do:
UPDATE $table SET credit = 0 WHERE... ?
Thanks in advance for any help :)
UPDATE $table SET credit = 0 WHERE ID > $ID
Will update any rows that have and ID greater than the variable $ID
If you only want to update the row with the maximum ID then use:
UPDATE $table SET credit = 0 WHERE ID = (select max(id) from $table)
Edit: As Eggyal correctly points out MySQL doesn't like a subquery on the same table as an update - but you can get around it nicely:
UPDATE $table
SET credit = 0
WHERE
credit='$credit'
AND statid='$statid'
AND userid='$userid'
AND ID = (select ID from (SELECT MAX(ID)as ID from $table) a)
And examples from my console:
mysql> select * from first;
+------+-------+
| id | title |
+------+-------+
| 1 | aaaa |
| 2 | bbbb |
| 3 | cccc |
| 4 | NULL |
| 6 | eeee |
+------+-------+
5 rows in set (0.00 sec)
mysql> update first set title='ffff' where id=(select max(id) from first);
ERROR 1093 (HY000): You can't specify target table 'first' for update in FROM clause
mysql> update first set title='ffff' where id=(select ID from (select max(id) as ID from first) a);
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from first;
+------+-------+
| id | title |
+------+-------+
| 1 | aaaa |
| 2 | bbbb |
| 3 | cccc |
| 4 | NULL |
| 6 | ffff |
+------+-------+
5 rows in set (0.00 sec)
Note: As the subquery within a subquery trick unlocks the original table, it is a good idea to run this within a transaction - if the table is unlocked from a query, it might have changed by the time it is updated - so it will be a good idea to use this type of query within a transaction.

MySql PHP results

Hi i'm working on some code with mysql and need to display the mysql results with php..
MySQL
select distinct(year(Cataloged_Date)) from records;
+------------------------+
| (year(Cataloged_Date)) |
+------------------------+
| 2009 |
+------------------------+
1 row in set (0.00 sec)
PHP
foreach($query->result() as $show){
$data[$i] = $show->Cataloged_Date;
$i++;
}
I'm using codeigniter for the php. Using $show->Cataloged_Date will not return anyting. I'm thinking its $show-> something to display the results...Just cant get it right now...
You need to provide a explicit name or alias for your field in the mysql query - when you apply functions to a column then it's non-obvious what the column name will be.
Try this:
//on MySQL
select distinct(year(Cataloged_Date)) as "Cat_Date" from records;
<?php
foreach($query->result() as $show){
$data[$i] = $show->Cat_Date;
$i++;
}
?>
You can apply an alias to any "value" on your select, be it a column name or the result of a function.
Just do
SELECT something AS YourAlias ...
To give you a clear example:
mysql> select 1;
+---+
| 1 |
+---+
| 1 |
+---+
1 row in set (0.00 sec)
#A simple value can be given an alias
mysql> select 1 as "Number";
+--------+
| Number |
+--------+
| 1 |
+--------+
1 row in set (0.00 sec)
mysql> select max(val) from my_values;
+----------+
| max(val) |
+----------+
| 4 |
+----------+
1 row in set (0.00 sec)
#A function
mysql> select max(val) as "max_val" from my_values;
+---------+
| max_val |
+---------+
| 4 |
+---------+
1 row in set (0.00 sec)
#or even a plain column
mysql> select val as "lav" from my_values;
+------+
| lav |
+------+
| 1 |
| 2 |
| 3 |
| 4 |
+------+
4 rows in set (0.00 sec)
Yes this is normally true but i'm using Codeigniter php framework. I did get it working with
$query->first_row() as $show
Then just echo $show and the results will display without you needing to know the rows name..

Categories