这是我的表结构
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。
答案 0 :(得分:4)
尝试一下,
SELECT MAX(CASE WHEN name = 'questions' THEN value END) questions,
MAX(CASE WHEN name = 'duration' THEN value END) duration
FROM pq_examsettings
答案 1 :(得分: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'];
}
答案 2 :(得分: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'];