简体   繁体   中英

Get record by value or get last record

I am trying to figure out if it is possible to get a record if there is a value otherwise grab the last record. I do currently have a solution using an if statement like the one below:

if (!empty($version)) {
    $sql = "SELECT `version` FROM `versioning` WHERE `id`='$itemID' AND `version`='$version' ORDER BY `version` DESC LIMIT 1";
}else{
    $sql = "SELECT `version` FROM `versioning` WHERE `id`='$itemID' ORDER BY `version` DESC LIMIT 1";
}

My question is: Is there was a way to do this in a single sql statement and if there is, what would be the pros or cons of doing it in a single statement?

To help clarify I am trying to figure out if it is possible to use one sql statement instead of an if statement to get either the specified version or if version is empty I would like to get the last version from the versioning table.

Yes you can do it by one sql like the following

$version = (!empty($version))?$version:'%%';
$sql = "SELECT `version` FROM `versioning` WHERE `id`='$itemID' AND `version` LIKE '$version' ORDER BY `version` DESC LIMIT 1";

by using one line, it can be useful if you like to change the conditions in the sql or add more fields or add another join statements ,,, all this you do not have to modify two sql lines

May not be using ANSI SQL statement but you can use a stored procedure though for passing the parameter and call that procedure instead in your app code like

create procedure usp_version (version varchar(10))
as
begin
if version is not null then
SELECT `version` FROM `versioning` 
WHERE `id`='$itemID' 
AND `version`='$version' 
ORDER BY `version` DESC 
LIMIT 1;
else
SELECT `version` 
FROM `versioning` 
WHERE `id`='$itemID' 
ORDER BY `version` DESC 
LIMIT 1;
end if;
end

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