【问题标题】:PDO: check tags presence in db and then insertPDO:检查数据库中存在的标签,然后插入
【发布时间】:2010-01-27 21:17:32
【问题描述】:

我正在为mysql 使用PDO 连接,我想对我用来检查tags 是否存在于数据库中的查询提出一些意见,并在它的情况下添加它不是。

// the tags are allready processed in $tags array 

$check_stmt = $connection->prepare ("SELECT * FROM tags WHERE tag_name = :tag_name");
$save_stmt = $connection->prepare ("INSERT INTO tags (tag_name) VALUES (:tag_name)");

foreach ($tags as $current_tag) {
    $check_stmt->bindParam (':tag_name', $current_tag, PDO::PARAM_STR, 32);
    $save_stmt->bindParam (':tag_name', $current_tag, PDO::PARAM_STR, 32);
    $check_stmt->execute ($current_tag);
    if ($check_stmt->rowCount() == 0) $save_stmt->execute ($current_tag);
}

我不熟悉数据库,所以我不确定查询是否得到很好的预测

【问题讨论】:

标签: php mysql tags pdo


【解决方案1】:

我会稍微调整一下您的选择查询,以进行优化:

SELECT 1 AS found FROM tags WHERE tag_name = :tag_name LIMIT 1

SELECTing * 从数据库向您的应用程序传输的数据(匹配记录中的所有字段)比必要的要多得多。只选择您需要的字段效率更高,在这种情况下,您似乎只是在检查是否存在,因此您不需要 任何 记录数据,因此选择 1。

LIMIT 1 将查询结果限制为一条记录,而不是 all 匹配的记录。更快的查询执行和更少的数据传输。

【讨论】:

    【解决方案2】:

    一些更脏的 MySQL 特定选项包括简单地使用 REPLACE INTO(不要)或 IGNORE 关键字与 INSERT 结合使用(建议)。 INSERT IGNORE 语法将比单独执行 SELECT 稍快。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      相关资源
      最近更新 更多