我有一个用户将一段数据输入我的数据库并将其命名为“Widget Title”。如果他将另一个项目称为“小部件标题”,另一个,另一个,当他在他的小部件列表中看到它们时,我想向他们展示如下:
每个重复的匹配项都有自己的附加递增ID。
您是在进入数据库的路上还是在显示列表的输出时执行此操作?
我可以使用算法吗?
答案 0 :(得分:0)
嗯...在保存前尝试这样的事情:
SELECT TOP 1 name FROM widgets WHERE name=@newname OR name LIKE (@newname + ' [0-9]' ORDER BY name DESC
这将为您提供“上次使用”的名称。
当然,这只会覆盖9个重复项,或者总共10个给定名称的实例。要使用此方法,您需要始终使用两位数后缀(02,03等)并更改LIKE子句以匹配。
(您没有指定RDBMS,因此这是为Microsoft SQL Server编写的,但IIRC的LIKE通配符语法与其他语法类似。)
答案 1 :(得分:0)
我刚用PHP将其用于输出,它似乎运行良好。你会做不同的事情吗?
$my_titles_array = array('Some Title',
'Widget Name',
'Widget Name',
'Some Other Title',
'Widget Name',
'Yet Another Title',
'Widget Name'
);
$counted_values_array = array_count_values($my_titles_array);
foreach ($my_titles_array as $title)
{
if($counted_values_array[$title] > 1)
{
$matches_array = array_keys($my_titles_array, $title);
$i=1;
foreach($matches_array as $match)
{
if($i != 1)
{
$my_titles_array[$match] = $title. ' '. $i;
}
$i++;
}
}
}
echo highlight_string(print_r($my_titles_array,true),true);
答案 2 :(得分:0)
declare @name nvarchar(40) declare @suffix int declare @currentName nvarchar(50) set @name = 'My Document' set @suffix = 1 set @currentName = @name while exists (select 1 from [table] where [name] = @currentName) begin set @currentName = @name + ' ' + cast(@suffix as nvarchar(10)) set @suffix = @suffix + 1 end
@name最终将成为“我的文档142”(如果还有141个其他副本)。请注意,如果您删除中间的副本(例如,副本76),则下一个副本将“填写”该孔并称为“我的文档76”。
这是T-SQL。
答案 3 :(得分:0)
我只是使用序列PK并在文本旁边向用户显示。