【问题标题】:Can anyone help me with this query?谁能帮我解决这个问题?
【发布时间】:2011-03-25 05:48:03
【问题描述】:

我将 id 存储在数据库的一行中,并且 id 用逗号分隔:

12,3,5,2,7

我正在尝试通过将字符串内爆并从另一个表中选择每个 id 来创建查询,但由于性能问题,我试图避免循环查询。反正有一个循环吗?我目前正在使用 mysqli 准备好的语句。

$stmt = $DBH->prepare("SELECT ids FROM list WHERE user = ?");
    $stmt->bind_param("s",$userid);
    $stmt->execute();
    $stmt->bind_result($ids);
        $stmt->fetch();

存储在 ids 中的只是一个数字列表,现在我如何查询另一个表以查找与列表中每个数字匹配的行,类似于标记系统。在进行查询之前,数字或数字的数量不是预先确定的或已知的。

EXAMPLE:

Table 1: Where the actual Information is stored

ID    Information

1     /*information stored for id number 1*/
2     /*information stored for id number 2*/
3     /*information stored for id number 3*/
4     /*information stored for id number 4*/
5     /*information stored for id number 5*/



Table 2: The users name and a list of id's stored (The ID_LIST will be constantly changing and expanding, the numbers contained will not be predefined.)

USER      ID_LIST

exampleuser    1,3,5
exampleuser2   1,4,12,22

第一个查询将从表 2 中获取 id 列表并将它们分开。然后我需要从表 2 中的 id 列表中的 id 中获取表 1 中每个 id 的信息。 但我试图避免循环,希望这足够具体,如果不是请告诉我。

【问题讨论】:

  • 在单个数据库字段中存储列表是错误的形式。正如您所发现的,它实际上使获取数据变得非常困难。 Please read up on database normalization 并纠正您的架构设计,它会让您的生活更加更轻松。
  • 是的,非常感谢您的帮助,我将其编辑得更具体一点,一秒钟。
  • 我更新了它,希望它更容易理解我想要完成的事情。

标签: php mysql mysqli prepared-statement


【解决方案1】:

您的其余代码将类似于

// This doesn't need to be a prepared statement
if ($result = $DBH->query("SELECT * FROM ids_table WHERE id IN ({$ids})")) {
    while ($row = $result->fetch_assoc()) {
        // Do whatever you want
    }
}

【讨论】:

    【解决方案2】:

    引用:-- “我的 id 存储在我的数据库的一行中,并且 id 用逗号分隔:”

    这基本上是一个糟糕的设计!

    您应该将 id 存储在另一个表的单个列中,其中的键是您现在表的键,加上 id。

    【讨论】:

      【解决方案3】:
      SELECT * FROM tbl WHERE FIND_IN_SET(id, '12,3,5,2,7')
      

      因此,您可以指定包含以逗号分隔的数字列表的任何字段作为FIND_IN_SET 的第二个参数

      【讨论】:

      • 好主意。看起来你实际上可以做到SELECT * FROM info WHERE FIND_IN_SET(id, (SELECT ids FROM users WHERE username = 'my_username'));
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      相关资源
      最近更新 更多