MYSQL 查询 - 根据同一 table 中另一列中的 DISTINCT 值 return 一列中所有值的简单方法?
MYSQL query - simple way to return all values from one column based on a DISTINCT value in another column in the same table?
我对这个有点摸不着头脑,我确信它很基础,但已经有一点点了。
如果我有两列 table,其结构基本上如下:
table: customer_per_store
pid, store_id
其中 pid 是唯一键,store_id 可以有多个重复值:
例如
1, 500
2, 500
3, 500
4, 505
5, 505
7, 0
8, 500
9, 0
将所有 pid 抓取到 DISTINCT store_id 但我们忽略值为 0 的 store_ids 的结果的正确查询是什么?
这很容易实现吗?我觉得这太容易了?
我想我可以在两个语句中完成,首先我得到所有 DISTINCT store_ids,将结果保存到一个数组,然后循环遍历该数组,对每个 store_id 执行查询] 并保存结果。
有没有更简单的方法可以在单个 mysql 查询中完成此操作?
理想情况下,在单个查询中我可以获得如下结果:
[500] => Array(
[0] => 1,
[1] => 2,
[2] => 3
...
),
[505] => Array(
[0] => 4,
[1] => 5
)
等?
我想你只是想要 group_concat()
:
select store_id, group_concat(pid)
from table t
where store_id <> 0
group by store_id;
你不想要这样的东西吗:SELECT pid, store_id FROM <your_database> WHERE store_id > 0 GROUP BY store_id
?
这会将所有在 store_id 下具有不同 store_id 的 pid 分组。
这可能不是您想要的确切查询,但我绝对认为您可以使用 GROUP BY
来实现。
由于调试输出,我假设您正在使用 php。
我认为您只是想将结果堆叠在一个关联数组中,其中键是 store_id。此示例使用 mysqli_query
,但您可以将其调整为 pdo。
$results_by_store_id = array();
$rs = mysqli_query("select * from customer_per_store where store_id <> 0");
while($r = mysqli_fetch_assoc($rs)) {
$results_by_store_id[$r['store_id']][] = $r['pid'];
}
print_r($results_by_store_id);
听起来您尝试使用错误的工具来完成工作,如果您使用 GROUP BY
变体,您仍然需要 post 将数据处理成数组。
你想要的查询很简单:
SELECT store_id, pid
FROM table t
WHERE store_id != 0
然后使用您选择的语言 运行 通过生成的 assoc 数组并从中构建您想要的数组。这是一些 php 代码:
$processed = [];
foreach($fetched as $row){
$processed[$row['store_id']][] = $row['pid']
}
我对这个有点摸不着头脑,我确信它很基础,但已经有一点点了。
如果我有两列 table,其结构基本上如下:
table: customer_per_store
pid, store_id
其中 pid 是唯一键,store_id 可以有多个重复值:
例如
1, 500
2, 500
3, 500
4, 505
5, 505
7, 0
8, 500
9, 0
将所有 pid 抓取到 DISTINCT store_id 但我们忽略值为 0 的 store_ids 的结果的正确查询是什么?
这很容易实现吗?我觉得这太容易了?
我想我可以在两个语句中完成,首先我得到所有 DISTINCT store_ids,将结果保存到一个数组,然后循环遍历该数组,对每个 store_id 执行查询] 并保存结果。
有没有更简单的方法可以在单个 mysql 查询中完成此操作?
理想情况下,在单个查询中我可以获得如下结果:
[500] => Array(
[0] => 1,
[1] => 2,
[2] => 3
...
),
[505] => Array(
[0] => 4,
[1] => 5
)
等?
我想你只是想要 group_concat()
:
select store_id, group_concat(pid)
from table t
where store_id <> 0
group by store_id;
你不想要这样的东西吗:SELECT pid, store_id FROM <your_database> WHERE store_id > 0 GROUP BY store_id
?
这会将所有在 store_id 下具有不同 store_id 的 pid 分组。
这可能不是您想要的确切查询,但我绝对认为您可以使用 GROUP BY
来实现。
由于调试输出,我假设您正在使用 php。
我认为您只是想将结果堆叠在一个关联数组中,其中键是 store_id。此示例使用 mysqli_query
,但您可以将其调整为 pdo。
$results_by_store_id = array();
$rs = mysqli_query("select * from customer_per_store where store_id <> 0");
while($r = mysqli_fetch_assoc($rs)) {
$results_by_store_id[$r['store_id']][] = $r['pid'];
}
print_r($results_by_store_id);
听起来您尝试使用错误的工具来完成工作,如果您使用 GROUP BY
变体,您仍然需要 post 将数据处理成数组。
你想要的查询很简单:
SELECT store_id, pid
FROM table t
WHERE store_id != 0
然后使用您选择的语言 运行 通过生成的 assoc 数组并从中构建您想要的数组。这是一些 php 代码:
$processed = [];
foreach($fetched as $row){
$processed[$row['store_id']][] = $row['pid']
}