MySQL 多对多表到表矩阵
我在 MySQL 中有一个多对多表 - 它可能看起来像:
A | B
1 | 1
1 | 2
1 | 3
3 | 4
3 | 5
4 | 1
4 | 2
4 | 5
等等。
你会注意到数字并不总是连续的,(A=1,3,4..) - 我正在寻找最快的方法将其转换为矩阵表,忽略没有数据的列和行(例如 A=2)。我的工作速度非常慢,因为我将每一行放入 php 中的一个单独的数组中,通过一个嵌套的 while 循环,它检查数组 A 和数组 B 的键是否与当前索引匹配:
while ($i <= $max_A) {
if (in_array($i, $array_A)) {
print ("<tr>");
while ($j <= $max_B) {
if (in_array($j, $array_B)) {
print ("<td>");
if (in_matrix($i, $j, $array_A, $array_B)) {
print ("1");
} else {
print ("0");
}
print ("</td>");
}
$j++;
}
print ("</tr>\n");
$j = $min_B;
}
$i++;
}
function in_matrix($search_value_A, $search_value_B, $array_A, $array_B) {
// Store the array keys matching search
$keys_A = array_keys($array_A, $search_value_A);
$keys_B = array_keys($array_B, $search_value_B);
foreach ($keys_A as $value) {
if (in_array($value, $keys_B)) {
return true;
}
}
return false;
}
也许我可以做更多做 MySQL 方面或加速搜索功能 - 我尝试找到一种方法来搜索二维数组(例如,如果给定行中的列 A = x AND 列 B = y,则返回 true)。
谢谢
I have a many to many table in MySQL - it can look something like:
A | B
1 | 1
1 | 2
1 | 3
3 | 4
3 | 5
4 | 1
4 | 2
4 | 5
etc.
You'll notice that the numbers are not always contiguous, (A=1,3,4..) - I am looking for the fastest way to turning this into a matrix table, ignoring columns and rows with no data (e.g. A=2). What I have working is painfully slow as I am taking each row into a separate array in php, going through a nested while loop, where it checks if the key for array A and array B match the current index:
while ($i <= $max_A) {
if (in_array($i, $array_A)) {
print ("<tr>");
while ($j <= $max_B) {
if (in_array($j, $array_B)) {
print ("<td>");
if (in_matrix($i, $j, $array_A, $array_B)) {
print ("1");
} else {
print ("0");
}
print ("</td>");
}
$j++;
}
print ("</tr>\n");
$j = $min_B;
}
$i++;
}
function in_matrix($search_value_A, $search_value_B, $array_A, $array_B) {
// Store the array keys matching search
$keys_A = array_keys($array_A, $search_value_A);
$keys_B = array_keys($array_B, $search_value_B);
foreach ($keys_A as $value) {
if (in_array($value, $keys_B)) {
return true;
}
}
return false;
}
Perhaps there is more I can do MySQL side or speed up the search function - I tried finding a way to searching a two-dimensional array (e.g. return true if Column A = x AND Column B = y in a given row).
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 SQL 中完成时,这称为数据透视,因为您要将行更改为列数据:
CASE 语句在结构上与 SWITCH 语句类似,但不支持失败。您必须为要作为列输出的每个行值定义一个 CASE 语句。
It's called pivoting the data when it's done in SQL, because you're changing row into columnar data:
The CASE statement is similar in structure to a SWITCH statement, but doesn't support fall through. You'll have to define a CASE statement for each row value you want to output as a column.