简体   繁体   中英

MySQL PHP SELECT WHERE id equals largest

Does anyone know how to do this in PHP?

SELECT (values, stuff) FROM database WHERE id = <Largest>

My table contains the columns ID , Code , Other , etc. I need to get the last/latest entry in the database (ie where the id is the largest). The ID is the key.

For example, in a table such as:

1, abc, ...
2, ghc, ...

It should return ghc .

SELECT * FROM table ORDER BY ID DESC LIMIT 1

There are two ways to do this.

1) Use of ORDER BY ID DESC + LIMIT 1

SELECT * FROM table ORDER BY id DESC LIMIT 1

ORDER BY ID DESC will sort your records in descending order, according to the id attribute.

LIMIT 1 will return you one (and the first) record.

Thus, returning you the record of the largest id in your table.

References: ORDER BY , LIMIT

2) Use of sub-query + MAX

SELECT * FROM table WHERE id = (SELECT MAX(id) FROM table);

First, (SELECT MAX(id) FROM table) will retrieve the largest id in your table.

Next, this largest id will be used in SELECT * FROM table WHERE id = to retrieve its record.

Thus, returning you the record of the largest id in your table.

References: Subquery , MAX

Examples: http://sqlfiddle.com/#!2/88518/1

订购他们desc,然后选择第一个

SELECT * FROM table ORDER BY id DESC LIMIT 0,1

First of all you need to lean more about mysql queries.
MySQL Tutorials

To get the max id you need to perform order by DESC query to get largets ID value. As your ID is primary key in the table.

select * from table_name order by ID desc limit 1

We can use query to simply get the MAX for id . Because doing ordering (by ORDER BY ) over an entire amount of records can be quite inefficient if we happen to have a lot of data, as it has to do a sort over all the data in the table. We can instead select the largest ID, then select the record that has that largest ID in the table:

SELECT Code FROM table WHERE ID=( SELECT MAX(ID) FROM table );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM