php - 选择像数组一样的位置

标签 php mysql

$tag = 'sky';

选择 tags 包含 $tag 的行:

$sql = "select * from images where tags like '%" . $tag . "%' order by date desc";

如果我有一个标签数组怎么办:

$tags = array('sky', 'earth', 'sun'); // max 3

foreach($tags as $tag) {
    $sql = "select * from images where tags like '%" . $tag . "%' order by date desc";
}

这是正确的方式吗,尤其是在性能方面。

images 大约有 20,000 行。

最佳答案

您可以使用正则表达式

$sql = "select * from images where tags REGEXP '" . implode('|', $tags) . "'  order by date desc";

您的最终结果将是:

select * from images where tags REGEXP 'sky|earth|sun' order by date desc

关于php - 选择像数组一样的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50296971/

相关文章:

php - phpmyadmin 中的 ID

PHP 和 MySQL - 使用 mysqli_real_escape_string 的正确方法

mysql - 如何修复具有许多表的数据库而不使用 Rails 匹配迁移

java - 返回非持久数据作为对象的一部分

java - JTable 不会通过 PropertyChangeListener 更新 repaint()

mysql - "Proper"存放MySQL数据库描述的地方

php - 脚本/队列不断耗尽内存

php - file_get_contents() 的问题

php - 无法与主机 mailtrap.io 建立连接 [php_network_getaddresses : getaddrinfo failed: No such host is known. #0]

php - 带下一个/上一个按钮的下拉菜单 php