所以我有这张桌子
TableTBL:
+--------+------+-------+
| ID | Col1 | Col2 |
+--------+------+-------+
| 1 | A | 30 |
| 2 | A | 20 |
| 3 | B | 40 |
| 4 | A | 10 |
+--------+------+-------+
现在我想基于Col1从Col2获取值,说我想要A的所有值,所以结果将是[30,20,10]。
我尝试了以下查询,但似乎无法正常工作:
SELECT DISTINCT Col2 FROM TableTBL WHERE Col1 = 'A' ORDER BY Col2 DESC;
我正在foreach循环中的php中使用它,因此这是带有php代码的查询:
$sql = "SELECT DISTINCT Col1 FROM TableTBL ORDER BY Col1 DESC;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql ))
{
echo "SQL statement failed";
}
else
{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result))
{
$rows[] = $row['Col1'];
}
for($i = 0; $i < count($rows) ;$i++)
{
echo $rows[$i].": {\n";
$sql = "SELECT DISTINCT Col2 FROM TableTBL WHERE Col1 = '$rows[$i]' ORDER BY Col2 DESC;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql))
{
echo "SQL statement failed";
}
else
{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
foreach($rows as $row) {
$arrList[] = $row['Col2'];
}
$text = implode("',' ", array_unique($arrList));
}
}
}
$text
是包含结果的字符串,用逗号分隔。
我在这里遇到的问题是,除了第一次迭代,我在所有结果中都得到了重复的结果,这给了我A 30,20,40,10,然后给了我B 30,20,40, 10。
答案 0 :(得分:1)
按照@Barmar的建议,使用一个查询:
$sql = "SELECT Col1,
GROUP_CONCAT(DISTINCT Col2 ORDER BY Col2 DESC SEPARATOR ', ') AS Col2
FROM TableTBL
GROUP BY Col1
ORDER BY Col1 ";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed";
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$arrList = array();
while ($row = mysqli_fetch_assoc($result)) {
$arrList[] = array(
'Col1' => $row['Col1'],
'Col2' => $row['Col2']
);
}
var_export($arrList);
}
输出:
array(
0 => array(
'Col1' => 'A',
'Col2' => '30, 20, 10',
),
1 => array(
'Col1' => 'B',
'Col2' => '40',
),
)
检查我的Demo query。
如果您不认识GROUP_CONCAT()
,他就是documentation