我在PHP中使用PDO对象来运行MYSQL查询,我一直在尝试处理查询以加快它的速度.查询如下,如我的PHP文件中所示:
$query =
"SELECT SQL_NO_CACHE f.position, s.item_id, s.item_type, s.title, s.caption, s.date
FROM apiv2.search_all s
INNER JOIN apiv2.tags t
USING(item_id, item_type)
LEFT JOIN apiv2.featured f
ON t.item_id = f.item_id AND t.item_type = f.item_type AND f.feature_type = :id
WHERE t.tag = 'FeaturedContent'
ORDER BY position IS NULL, position ASC, date";
$mysql_vars[':id'] = $id;
$stmt = $connection->prepare($query);
$stmt->execute($vars);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
Run Code Online (Sandbox Code Playgroud)
此查询的运行方式有很大不同,具体取决于我是否包含ORDER BY子句,但仅限于MYSQL控制台:
- MYSQL Console with ORDER BY: 1.07 sec
- starting 0.000141
- Opening tables 0.001416
- System lock 0.000003
- …Run Code Online (Sandbox Code Playgroud) 尝试使用在MySQL服务器上运行SQL查询的PHP脚本将数据库复制到新数据库中.我所熟悉的代码是:
$dbh->exec("CREATE DATABASE IF NOT EXISTS $new_news CHARACTER SET UTF8;");
$results = $dbh->query("SHOW TABLES FROM $old_news");
$table_list = $results->fetchAll(PDO::FETCH_NUM);
foreach($table_list as $table_row){
foreach($table_row as $table){
$results = $dbh->query("SELECT table_type FROM information_schema.tables where table_schema = '$old_news' and table_name = '$table'");
$table_type = $results->fetch(PDO::FETCH_ASSOC);
$table_type = $table_type['table_type'];
if($table_type == 'BASE TABLE'){
echo "Creating table $table and populating...\n";
$dbh->exec("CREATE TABLE $new_news.$table LIKE $old_news.$table");
$dbh->exec("INSERT INTO $new_news.$table SELECT * FROM $old_news.$table");
}else if($table_type == 'VIEW'){
//echo "Creating view $table...\n";
//$dbh->exec("CREATE VIEW $new_news.$table LIKE $old_news.$table"); …Run Code Online (Sandbox Code Playgroud)