作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 mariadb 中有一个这种结构的表,
CREATE TABLE `items` (
`id` char(36), `route` varchar(255), `value` text,
PRIMARY KEY (`id`),
UNIQUE KEY `route` (`route`)
)
我使用 route
列来获取用户友好的 url,例如 http://www.examle.com/this-is-the-route-of-an-item
当用户创建新项目时,除了省略空格和非法字符外,我想“捕获”为新项目选择的路由正在使用的情况,并生成有效路由。
例如,如果 route-of-an-item
已经在使用中,我会回退到 route-of-an-item-a
,或者 route-of-an-item-b
等
天真的解决方案可能是在循环中查询数据库,例如(某种伪代码):
var additionalChars = "";
while (db.query("select count * from `items` where `route`='" + route + "-" + additionalChars + "'"))
additionalChars = nextAdditionalChars(additionalChars);
finalRoute = route + '-' + additionalChars;
由于这涉及多次查询数据库,我想到了另一种解决方案。
var additionalChars = "";
var usedRoutes = db.query("select `route` from `items` where `route` like '" + route + "%'");
while(usedRoutes.contains(route + '-' + additionalChars))
additionalChars = nextAdditionalChars(additionalChars);
finalRoute = route + '-' + additionalChars;
有没有更好的方法来解决这类问题?
我认为第二种解决方案的性能更好是否正确?
如果我使用第二种解决方案,我是否应该在路由字段中添加全文索引?
最佳答案
您可以按路线降序对查询进行排序,并且只检索和检查一项。在您的伪代码中,这看起来像:
var additionalChars = "";
var usedRoutes = db.query("select `route` from `items` where `route` like '" + route + "%' order by `route` desc limit 1");
if(usedRoutes.route is already in use)
additionalChars = nextAdditionalChars(additionalChars);
finalRoute = route + '-' + additionalChars;
关于mysql - 循环生成唯一的 url 友好路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40490855/
我是一名优秀的程序员,十分优秀!