简体   繁体   English

选择内部联接,sql和php的group_concat

[英]select inner join, group_concat of sql and php

I have the following query: 我有以下查询:

$myquery = mysql_query("SELECT p.name, GROUP_CONCAT(m.name) as products
                    FROM access as pm
                    INNER JOIN seller as p on p.id = pm.id_seller
                    INNER JOIN products as m on m.id  = pm.id_product
                    WHERE p.id = '".$_COOKIE['id_seller']."'");

Which returns me this array: 返回我这个数组:

Array (
[0] => Seller Name [name] => Seller Name
[1] => Product1 [products] => Product1
);

How should I query the database correctly? 我应该如何正确查询数据库? Thanking in consideration that I have 3 tables (products, access and seller). 感谢考虑到我有3个表(产品,访问权和卖方)。 What I'd like to achieve is to attribute (access) one or more products to a seller. 我想要实现的是将一种或多种产品归因于(卖方)卖方。

And how my drop-down list populate code would look like? 以及我的下拉列表填充代码的外观如何?

<?php
      echo'<select name="productaccess">';
foreach($myquery as $product) {
      echo'<option value="'.$product.'">'.$product.'</option>';
}
      echo'</select>';
?> 

Thanks! 谢谢!

If you want the products for just one seller, you don't need grouping at all. 如果您只需要一位卖家的产品,则根本不需要分组。 Just list the names of the products: 只需列出产品名称:

$myquery = mysql_query("SELECT m.name
                    FROM access as pm
                    INNER JOIN seller as p on p.id = pm.id_seller
                    INNER JOIN products as m on m.id  = pm.id_product
                    WHERE p.id = '".$_COOKIE['id_seller']."'");

Now $myquery is only a resource identifier, not the results, so you get the latter with mysql_fetch_array() like this: 现在$myquery只是一个资源标识符,而不是结果,因此可以通过mysql_fetch_array()获得后者,如下所示:

while($row=mysql_fetch_array($myquery)) {
    echo'<option value="'.$row['name'].'">'.$row['name'].'</option>';
}

GROUP_CONCAT is used with a GROUP BY clause, which is not present. GROUP_CONCAT与不存在的GROUP BY子句一起使用。 Add a 'GROUP BY p.name' to your SQL. 在您的SQL中添加一个“按名称组”。 That will make the above SQL return a single row, with the seller name and the product names, separated by commas. 这将使上面的SQL返回一行,其中卖方名称和产品名称以逗号分隔。 Then burst the product names into an array, which you then feed to the foreach loop. 然后将产品名称分解为一个数组,然后将其馈入foreach循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM