带有2个变量的循环SQL查询

时间:2015-11-01 13:56:27

标签: php mysql loops

我有一个包含3个字段的表(标签),activityID,placeID,tagID(以及第4个,ID为PKey)。我想使用2个数组,一个地方和一个标签搜索此表。对于每个匹配,我想返回activityID。然后,我想在另一个表(活动)中使用此活动ID列表与每个相同的PlaceID数组。我开始把它放在一起作为循环,但我看到许多事情说不要这样做。我以为我需要使用临时表,但也可能不需要。我还在努力用循环来做这件事而不是努力做出一些不好的做法,无论如何我认为我发布了一般的想法,看看有人能指出我正确的方向......这段代码不起作用,但显示了一般的想法..EDIT ......我只是想在第一部分解决循环,第二部分我需要留下作为循环

$places = array("London","Madrid","Paris","Rome"); 
$tags = array("Shopping","Sight","Bar","Club");
$num_places = count($places);
$num_tags = count($tags);

/* I want to remove the loop from this section */
$counterP = 0; 
while($counterP <= ($num_places)) {
  $counterT = 0; 
  while($counterT <= ($num_tags)) {
    $conn->query('INSERT INTO temp (activityID)
    SELECT activityID, placeID
    FROM tags
    WHERE placeID = "'.$place[$counterP].'" AND tagID = "'.$tag[$counterT].'"');
  $counterT++;
  }
$counterP++;
}

/* This section will stay in a loop */
$counterP = 0; 
while($counterP <= ($num_places)) {
$sql_interests = 'SELECT a.summary, a.image, a.link
  FROM activity a 
  LEFT JOIN temp t
  ON t.activityID = a.activityID 
  WHERE a.placeID = "'.$place[$counterP].'"';

  $interests = array();
  $interests_result = $conn->query($sql_interests);
  if ( !empty($interests_result)) {
    while($interests_row = $interests_result->fetch_assoc()) {
      $interests[] = array($interests_row["summary"],$intersts_row["image"],$interests_row["link"]);
    }
    /* do stuff with data */
  }
  $counterP++;
}

2 个答案:

答案 0 :(得分:2)

由于我目前仅限于手机访问,我只建议您做以下事情:

  1. 使用“','”作为分隔符加入两个数组。
  2. 使用IN()函数编写where子句。喜欢:where placeID IN('London','Madrid','Paris','Rome')和tagID IN(...)
  3. 这应该可以提供您所需的结果。

答案 1 :(得分:2)

mysql唯一的方法。 where子句使用in子句过滤标签,连接将您带到活动表。 at只是简单阅读或懒惰(如我)的别名

select a.* 
from activity a
join tags t
on t.activityID=a.activityId
where t.tagID in ('sightseeing','parks')
and t.placeID in ('Istanbul','Paris');

+----+------------+---------+---------------------------+
| ID | activityID | placeID | summary                   |
+----+------------+---------+---------------------------+
|  4 | 444        | Paris   | See Arc D'Triumph         |
|  6 | 666        | Paris   | See Eifel Tower           |
|  8 | 888        | Paris   | Walk through Central Park |
+----+------------+---------+---------------------------+
3 rows in set (0.01 sec)
相关问题