如何在JOIN中包含其他select语句? PHP - MySQL

时间:2015-12-02 10:42:23

标签: php mysql join

我有两个表格,如:

tagmap

===============
 item | tagid
---------------
 1111 |   101
 1111 |   102
 2222 |   101
 2222 |   103
 3333 |   104
 4444 |   105
 4444 |   106
 5555 |   101
 5555 |   103
==============

item + tagid =复合主键

风味

===============
 id  | flavor
---------------
 101 | flavorA
 102 | flavorB
 103 | flavorC
 104 | flavorD
 105 | flavorE
 106 | flavorF
===============

id =主键

我运行PHP + MySQL。我有一个类似的查询

SELECT DISTINCT GROUP_CONCAT(a.tagid ORDER BY a.tagid) tags
  FROM tagmap a
  JOIN tagmap b
    ON b.item = a.item
   AND b.tagid <= a.tagid
 WHERE b.tagid = '101'
 GROUP
    BY a.item;

我将它存储到变量$query,它会返回像;

这样的数据
flavorA,flavorB
flavorA,flavorC

在PHP中,我使用

$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
    $tag = $rowa['tags'];
    echo $tag."<br>";
}

打印结果的代码。但与此同时,我想要味道ID,我想存储到另一个变量,如;

$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
    $tag = $rowa['tags'];
    $tagid = $rowa['tagid'];//what I am looking for.
    echo $tag."<br>";//echoes flavorA,flavorB
    echo $tagid."<br>";//want to echo 101,102
}

在每个foreach循环中,我想将id以CSV格式存储在一个变量中,flavor以CSV格式存储在另一个变量中。例如,当它返回flavorA,flavorB时,我想将其存储在$tag(已经在做)和101,102$tagid(我想要的其他内容)。

我该怎么做?我的意思是,在哪里/如何包含select flavor语句以及如何获取它?

2 个答案:

答案 0 :(得分:0)

所以,回答你的问题......

SELECT t.item
     , f.flavor 
  FROM tagmap t 
  JOIN flavors f 
    ON f.id = t.tagid;
+------+---------+
| item | flavor  |
+------+---------+
| 1111 | flavorA |
| 1111 | flavorB |
| 2222 | flavorA |
| 2222 | flavorC |
| 3333 | flavorD |
| 4444 | flavorE |
| 4444 | flavorF |
| 5555 | flavorA |
| 5555 | flavorC |
+------+---------+

答案 1 :(得分:0)

只需在SQL查询中包含两个GROUP_CONCAT()列,按ITEM分组。如果需要获取不同的结果集,请在派生表子查询中设置它:

SELECT DISTINCT tagids, flavors    
FROM
   ( SELECT t.item,
            GROUP_CONCAT(DISTINCT t.tagid ORDER BY t.tagid) AS tagids,
            GROUP_CONCAT(DISTINCT f.flavor ORDER BY f.flavor) AS flavors
     FROM tagmap t 
     INNER JOIN flavors f ON f.id = t.tagid
     GROUP BY t.item
   ) As grptbl

SQL OUTPUT

tagids     flavors
101,102    flavorA,flavorB
101,103    flavorA,flavorC
104        flavorD
105,106    flavorE,flavorF

然后让PHP引用关联数组中的tagidsflavors列。 注意:我使用mysqli_而不是已弃用的(现已停用在PHP 7中)mysql_ *函数。

$result = mysqli_query($con, $query);

if ($result) {

    /* fetch associative array */
    while ($row = mysqli_fetch_assoc($result)){
       echo $row['flavors']."<br>"; //echoes flavorA,flavorB
       echo $row['tagids']"<br>";   //echoes 101,102
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($con);