3

这是我的表结构

id 名称 值
1 问题 50
2 持续时间 120

现在,我想根据名称显示值。我无法正确执行 sql 语句。这就是我所做的:

$qry = "SELECT * FROM (
SELECT (SELECT value FROM pq_examsettings) as duration,
       (SELECT value FROM pq_examsettings) as questions
 ) ";
$result= mysql_query($qry);
$row = mysql_fetch_array($result);
$duration = $row['duration'];
$questions = $row['questions'];

有人帮助我了解如何进行查询,以便我的 $duration 和 $questions 变量显示 120 和 50。

4

3 回答 3

4

试试这个,

SELECT  MAX(CASE WHEN name = 'questions' THEN value END) questions,
        MAX(CASE WHEN name = 'duration' THEN value END) duration 
FROM    pq_examsettings
于 2013-05-01T15:58:53.100 回答
0

使用 mysqli 或 pdo 函数 mysql_* 函数已被正式弃用:

$mysqli = new mysqli($dbserver, $dbmanager, $dbpass, $dbname);
if($mysqli->connect_errno) {
    echo "Error connecting to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$query = $mysqli->query("SELECT * FROM pq_examsettings");
if($query->num_rows){
$new_row = array();
while($row = $query->fetch_assoc()){
    foreach($row as $key => $value){
        if($key == 'name'){
            $array_key = $value;
        }
        if($key == 'value'){
            $new_row[$array_key] = $value;
        }
    }
}
$duration = $new_row['duration'];
$questions = $new_row['questions'];
}
于 2013-05-01T15:59:03.643 回答
0

我对 MySQL 不够熟悉,不知道一种将行转换为列并在一次选择中返回结果的简单方法——看起来 JW 给出了一个答案。

另一种选择是只进行两次数据库调用:

$qry = "SELECT value FROM PQ_EXAMSETTINGS WHERE NAME = 'duration'";
$result= mysql_query($qry);
$row = mysql_fetch_array($result);
$duration = $row['value'];

$qry = "SELECT value FROM PQ_EXAMSETTINGS WHERE NAME = 'questions'";
$result= mysql_query($qry);
$row = mysql_fetch_array($result);
$questions = $row['value'];
于 2013-05-01T16:05:34.203 回答