我有一个名为tags
的表格,如下所示:
/ tags
+----+------+--------------------------------------------+
| id | name | explanation |
+----+------+--------------------------------------------+
| 1 | PHP | It is a server-side scripting language |
| 2 | C++ | It is a middle-level programming language |
| 3 | HTML | It is a markup language |
| 4 | CSS | It is a style sheet language |
| 5 | JS | It is a prototype-based language |
+----+------+--------------------------------------------+
我也有这样的字符串:
$str = "PHP , CSS";
现在我需要检查数据库中是否存在PHP
和CSS
?一般来说有两种情况:
True
:字符串中的所有标签都存在于数据库中。False
:数据库中不存在字符串中的一个或多个标记。我可以爆炸该字符串并创建这些标记的数组:
$tags = trim(explode(",",$str)); // Array ( [0] => PHP [1] => CSS )
然后创建多个查询以分别检查每个查询:
$i= count($tags);
for($i; $i <= 0; $i--){
$query .= "SELECT count(1) FROM `tags` WHERE `name` =".$tags[$i]." UNION ALL";
}
$query = rtrim($query, "UNION ALL"); // to remove last 'UNION ALL' which is redundant
但是我的方法似乎很慢..因为有时会有5个标签(然后有5个查询)。现在我想知道,还有更好的方法吗?
答案 0 :(得分:2)
你可以这样做。试试这个:
您的新查询:
$str = "PHP , CSS";
$search = join(",", trim(explode(",",$str)));
$sql = "SELECT count(1) FROM `tags` WHERE `name` IN ($search)";
$qry = mysql_query($sql);
if(sizeof($qry) == sizeof(explode(",",$str)))
echo "True";
else
echo "False";
我想现在你可以做到。
答案 1 :(得分:1)
您也可以使用IN(&#39; PHP&#39;,&#39; CSS&#39;)并检查计数是否匹配。试试 -
$tags = explode(",",$str);
$tags = array_map('trim', $tags);
$query = "SELECT count(1) FROM `tags` WHERE `name` IN ('" . implode("','", $tags) . "')";
执行查询后匹配计数。
if($countOfResult === count($tags));
答案 2 :(得分:0)
你可以试试这个:
SELECT COUNT(name),name FROM `tags` WHERE name in ('PHP','CSS') group by name;