选择数组

时间:2018-05-11 16:57:10

标签: 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行。

3 个答案:

答案 0 :(得分:1)

您可以使用regexp

$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

答案 1 :(得分:0)

使用查询中的OR为您的查询添加多个标记

$sql = "select * from images where tags like '%" . $tag[0] . "%' OR tags like '%" . $tag[1] . "%' OR tags like '%" . $tag[2] . "%' order by date desc";

您不需要使用foreach来运行查询

更新1

$comma_separated = "('" . implode("','", $tags) . "')";
$sql = "select * from images where tags IN ".$comma_separated;

最有效的方式

REGEXP可能效率更高,您必须以自己为基准

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

答案 2 :(得分:0)

这是一个可能的实现,您不必知道数组大小。

$tags = array('one', 'two');
$sql = "select * from images where tags like '%" . implode("%' OR tags like '%",$tags) . "%' order by date desc";
相关问题