簡體   English   中英

帶2個變量的循環SQL查詢

[英]Looped SQL queries with 2 variables

我有一個表(標簽),其中包含3個字段,即activityID,placeID,tagID(第四個字段為PKey,ID)。 我想使用2個數組(位置之一和標簽之一)搜索此表。 對於每個匹配,我想返回activityID。 然后,我想在另一個表(活動)中將此ActivityID列表與每個相同的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++;
}

由於我目前只能使用手機,因此我只能建議您做以下事情:

  1. 將兩個數組以“','”作為分隔符。
  2. 使用IN()函數編寫where子句。 像:whereplaceID IN('London','Madrid','Paris','Rome')和tagID IN(...)

這應該給您所需的結果。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM