得到错误:SQLSTATE [42S22]:找不到列:1247

时间:2019-01-31 08:23:46

标签: php mysql database random

我的问题涉及另一个讨论分支-https://keithito.com/LJ-Speech-Dataset/

我有一个简单的一列表:

+-----------------------+
| keywords              |
+-----------------------+
| Some text 1           |
| Some text 2           |
| Some text 3           |
| Some text 4           |
| Some text 5           |
| Some text 6           |
| Some text 7           |
| Some text 8           |
| Some text 9           |
| Some text 10          |
| Some text 11          |
| Some text 12          |
| ...                   |
| Some text 1200000     |
+-----------------------+

我正在尝试使用#Riedsio在上面一行中建议的代码对一定数量的随机行执行请求,

SELECT name
  FROM random AS r1 JOIN
       (SELECT CEIL(RAND() *
                     (SELECT MAX(id)
                        FROM random)) AS id)
        AS r2
 WHERE r1.id >= r2.id
 ORDER BY r1.id ASC
 LIMIT 1

我的代码如下:

<?php

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
    }
}

$servername = "localhost";
$username = "admin";
$password = "admin_pass";
$dbname = "db_name";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//    $stmt = $conn->prepare("SELECT keywords FROM my_keywords");
    $stmt = $conn->prepare("SELECT keywords FROM my_keywords AS r1 JOIN (SELECT CEIL(RAND() * (SELECT MAX(id) FROM my_keywords)) AS id) AS r2 WHERE r1.id >= r2.id ORDER BY r1.id ASC LIMIT 1");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
            echo $v;
        }
    }

catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;

?>

结果得到以下错误:“错误:SQLSTATE [42S22]:找不到列:1247不支持引用'id'(项目列表中的向前引用)”。

我只是从MySQL开始,所以请不要被这个愚蠢的问题所冒犯,谢谢您的帮助。

0 个答案:

没有答案