gpt4 book ai didi

php - 使用分号分隔字符串的 Mysql 搜索

转载 作者:可可西里 更新时间:2023-11-01 08:31:39 25 4
gpt4 key购买 nike

我有 2 个看起来像这样的表

table A            table B
id | data id | features
--------- --------------
1 | blue 1A | 1;2
2 | red 2B | 1;2;3
3 | yellow 3B | 3;1
...... ......

我打算做的是这样的,我查询一个表。遍历结果数组并使用分号分隔符分解数据。然后循环遍历新数组并查询它以获取数据(注意下面的代码未测试)

$sql = "SELECT * FROM `tableB` WHERE `id`= '2B' LIMIT 1";

$query = $db->query($sql);

while ($row = mysql_fetch_array($query)) {

$arr = explode(';', $row['features']);

for ($i = 0; $i < sizeof($arr); $i++)
{
$sql2 = "SELECT * FROM `tableA` WHERE `id`="'.$arr[$i].'"";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
}
}

print_r($r);

有没有一种方法可以在 mysql 中实现这一点,我将 tableB 中的列与 tableA 中的 ID 相匹配?或者可能不使用嵌套循环?性能是关键。因为两个表都有超过 25k 行的数据。

提前致谢

最佳答案

检查这段代码。减少了几个循环。

$sql = "SELECT * FROM `tableB` WHERE `id`= '2B' LIMIT 1";
$query = $db->query($sql);
$arr = explode(';', $row['features']);

$str = implode(",", $arr);

$sql2 = "SELECT * FROM `tableA WHERE id IN ({$str});";

$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}

关于php - 使用分号分隔字符串的 Mysql 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24669714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com