Mysql 从多行中选择多个值

Mysql 从多行中选择多个值,mysql,sql,Mysql,Sql,无法确定如何获得此结果: ProductID Variantno 53121 5197, 5198,5199 从这个数据收集 ProductID Variantno 53121 5197 53121 5198 53121 5199 尝试使用group by,但没有很好的结果,total sql noob…尝试此 SELECT ProductID, GROUP_CONCAT(Var

无法确定如何获得此结果:

ProductID       Variantno
53121           5197, 5198,5199
从这个数据收集

ProductID       Variantno
53121           5197
53121           5198
53121           5199
尝试使用group by,但没有很好的结果,total sql noob…

尝试此

SELECT 
  ProductID,
  GROUP_CONCAT(Variantno)
FROM tbl
GROUP BY ProductID
试试这个:

WITH cte AS (
    SELECT 
        ProductID,
        CAST('<r>' + REPLACE(variantNo, ',', '</r><r>') + '</r>' AS XML) AS VariantNos
    FROM TestTable
)
SELECT 
    ProductID,
    xTable.xColumn.value('.', 'VARCHAR(MAX)') AS VariantNo
FROM cte
CROSS APPLY VariantNos.nodes('//r') AS xTable(xColumn) 

不显示代码和数据库。我假设您正在使用php和mysql。 我已经运行并测试了这段代码,它是有效的。这意味着它将为你工作。我的连接是PDO。如果你仍然有问题,请给我一声喊叫

<?php



// pdo connection



$db = new PDO (

    'mysql:host=localhost;dbname=sectona_db;charset=utf8', 

    'root', // username



    'root90' // password

);

?>




                    <?php

Echo 'Data Output:<br>';
include("pdo.php");

$result = $db->prepare("SELECT * FROM product where id='123'");
        $result->execute(array());



while ($r = $result->fetch()) 
                       {
//$data = htmlentities($r['product'], ENT_QUOTES, "UTF-8");






?>

<?php echo htmlentities($r['product'], ENT_QUOTES, "UTF-8");?>,



<?php } ?>

考虑GROPY-CONTAT返回的结果是一个字符串,就像一个注意事项:不要忘记选择答案:您正在处理的哪一个RDBMS?mysql还是sql server?或者你需要一个跨rdbms的解决方案?@Robert yup,谢谢!
<?php



// pdo connection



$db = new PDO (

    'mysql:host=localhost;dbname=sectona_db;charset=utf8', 

    'root', // username



    'root90' // password

);

?>




                    <?php

Echo 'Data Output:<br>';
include("pdo.php");

$result = $db->prepare("SELECT * FROM product where id='123'");
        $result->execute(array());



while ($r = $result->fetch()) 
                       {
//$data = htmlentities($r['product'], ENT_QUOTES, "UTF-8");






?>

<?php echo htmlentities($r['product'], ENT_QUOTES, "UTF-8");?>,



<?php } ?>