简体   繁体   English

按值获取记录或获取最新记录

[英]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语句的解决方案,如下所示:

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? 我的问题是:有没有办法在单个sql语句中执行此操作,如果有,在单个语句中执行此操作的利弊是什么?

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. 为了帮助澄清,我试图找出是否可以使用一个sql语句而不是if语句来获取指定versionversion为空,我想从versioning表中获取最新version

Yes you can do it by one sql like the following 是的,您可以通过如下一条SQL来做到这一点

$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 通过使用一行,如果您想更改sql中的条件或添加更多字段或添加另一个join语句,这将很有用,而您不必修改两条sql行

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 可能未使用ANSI SQL语句,但是您可以使用存储过程来传递参数,然后在您的应用程序代码中调用该过程,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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