我有一张如下表格;
表-A
|-------+---------|
| tagid | tagname |
|-------+---------|
| 1234 | taga |
|-------+---------|
| 2345 | tagb |
|-------+---------|
| 3456 | tagc |
|-------+---------|
| 4567 | tagd |
|-------+---------|
表-B
|-------+--------+-----------|
| id | entry | tags |
|-------+--------+-----------|
| 1111 | entry1 | taga,tagb |
|-------+--------+-----------|
| 2222 | entry2 | tagb,tagc |
|-------+--------+-----------|
| 3333 | entry3 | tagd |
|-------+--------+-----------|
| 4444 | entry4 | tage |
|-------+--------+-----------|
每当我向 table_b 添加条目时,我想检查 table_a 中是否存在标记。我现在所做的是将条目的标签放入一个数组中,并检查每个标签的行数,例如,
$msg = "";
$tagarray = array("taga","tagb","tagc");
foreach($tagarray as $tags){
$query = "SELECT * FROM `table_a` WHERE tagname = '$tags'";
$result = mysql_query($query);
$numrows = mysql_num_rows($result);
if($numrows == 0){
$msg .= $tags.",";
}
}
通过这种方式,我可以捕获所有未重新发送到$msg
变量的标签。但在这里,我需要对每个标签执行单独的检查。有没有其他更好的方法来实现同样的目标?我希望在table_a
中添加条目时抓住table_b
中不存在的所有标记。
答案 0 :(得分:0)
要搜索具有IN Operator的列中的多个值,您可以使用implode使用逗号将数组转换为正确的格式。
答案 1 :(得分:0)
试试这个:
$msg = "";
$tagarray = array("taga","tagb","tagc");
$c=0;
$tagStr='';
//create string for sql query in IN format
foreach($tagarray as $tags)
{
if($c==0)
$tagStr.="'$tags'";
else
$tagStr.=",'$tags'";
$c++;
}
$msg=implode(",",$tagarray );
$query = "SELECT * FROM `table_a` WHERE tagname IN($tagStr)";
$result = mysql_query($query);
$numrows = mysql_num_rows($result);
//existed tags
if($numrows != 0){
while ($row = mysql_fetch_assoc($result)) {
//replace them from original string
$msg=str_replace($row["tagname"],"",$msg);
if($msg[count($msg)]==",")
$msg[count($msg)]='';
if($msg[0]==",")
$msg[0]="";
}
}
$msg=chop($msg); //string ready for insert
答案 2 :(得分:-1)
尝试使用以下内容,
$msg = "";
$tagarray = array("taga","tagb","tagc");
$query = "SELECT * FROM `table_a` WHERE tagname IN (".implode(',',$tagarray).")";
$result = mysql_query($query);
$numrows = mysql_num_rows($result);
if($numrows == 0){
$msg .= implode(',',$tagarray);
}