php - 具有 2 个变量的循环 SQL 查询

标签 php mysql loops

我有一个表(标签),有 3 个字段:activityID、placeID、tagID(第四个 ID 作为 PKey)。我想使用 2 个数组(其中一个位置和一个标签)来搜索该表。对于每场比赛,我想返回 ActivityID。然后,我想在另一个表(事件)中使用此 ActivityID 列表以及每个相同的 PlaceID 数组。我开始将其作为循环放在一起,但我看到很多东西都说不要这样做。我想我需要使用临时表,但这也可能不是必需的。无论如何,我也正在努力用循环来做到这一点,所以与其努力做一些实践不佳的事情,我想我应该发布总体思路,看看是否有人可以指出我正确的方向......这段代码不是工作但显示了总体思路..编辑...我只想解决第一部分中的循环,第二部分我需要保留为循环

$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++;
}

最佳答案

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)

关于php - 具有 2 个变量的循环 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33462916/

相关文章:

php - jquery @mention 使输出成为链接

mysql - 删除具有多个值的 SQL 行,其中 ID 在另一个表中不匹配

mysql - 计算复杂查询的结果

javascript - 输入到文本字段的一系列数字的总和和平均值

php - 在 PHP 中正确使用变量作用域

php - 从 php 服务器接收文本文件到 ios 应用程序

php - 如果电子邮件未确认,则从数据库中删除用户

mysql - WHERE语句查找一个月内的所有记录?

java - 用于 3 个嵌套循环的大 O

python - 如何在 Python 的 For 循环中添加输入请求的数字?