如何组合两个MySQL查询以在一个表行中显示结果

时间:2016-06-20 13:56:09

标签: mysql

我有两个单独的查询,显示两个表中的结果。我想在一个表中显示结果。如何让它显示这些数据?

所以在第一行我想要

  • 2
  • GE 32,768 kHz SMD
  • 12,87112
  • Rezonator kwarcowy KX-327S 32,768 kHz 12.5pF,20 / -0,042 / 50K
  • Rezonatory filtryiźródłasezęstotliwości> Rezonatory kwarcowe(此处添加新行而不是“ - ”
  • 12195
  • 1
  • 1
  • 1.190000

这就是它现在的样子。我想添加另一栏“ Nazwa kategorii

enter image description here

<?php 
    $result = mysql_query('SELECT 
        prodlang.id_product AS "idprod", 
        prodlang.name AS "nazwa", 
        prod.price AS "cena", 
        prod.minimal_quantity AS "moq", 
        prod.ean13 AS "nazwag", 
        prod.reference AS "kod", 
        prod.quantity AS "ilosc",
        prod.active AS "aktywny" 
        FROM pstest_product_lang prodlang
        INNER JOIN pstest_product prod
        ON prodlang.id_product=prod.id_product
        limit 10');

        while ($row = mysql_fetch_array($result)) echo('<tr><td>'.$row['idprod'].'</td><td>'.$row['kod'].'</td><td>'.$row['nazwag'].'</td><td>'.$row['nazwa'].'</td><td> - </td><td>'.$row['ilosc'].'</td><td>'.$row['aktywny'].'</td><td>'.$row['moq'].'</td><td>'.$row['cena'].'</td></tr>');

?>
<?php 
    $results = mysql_query('SELECT 
        prodcat.id_product AS "idprod", 
        catlang.name AS "nazwacat" 
        FROM pstest_category_product prodcat
        INNER JOIN pstest_category_lang catlang
        ON prodcat.id_category=catlang.id_category
        ORDER BY idprod
        limit 10');

        while ($row = mysql_fetch_array($results)) echo('<tr><td>'.$row['idprod'].'</td><td>'.$row['nazwacat'].'</td></tr>');                                               
?>

1 个答案:

答案 0 :(得分:1)

您可以将 group_concat 分组一起使用。有关mor信息,请参阅group by doc。我更改了您的查询并希望它能够正常运行:

SELECT 
        prodlang.id_product AS "idprod", 
        prodlang.name AS "nazwa", 
        prod.price AS "cena", 
        prod.minimal_quantity AS "moq", 
        prod.ean13 AS "nazwag",
        t2.nazwacat as "nazwacat", 
        prod.reference AS "kod", 
        prod.quantity AS "ilosc",
        prod.active AS "aktywny"
        FROM pstest_product_lang prodlang
        INNER JOIN pstest_product prod
        ON prodlang.id_product=prod.id_product
        join (
        SELECT 
        prodcat.id_product AS "idprod", 
        Group_concat(catlang.name) AS "nazwacat" 
        FROM pstest_category_product prodcat
        INNER JOIN pstest_category_lang catlang
        ON prodcat.id_category=catlang.id_category
group by prodcat.id_product
) t2 on t2.idprod=prodlang.id_product
        limit 10