Mysql减少了查询次数

时间:2011-01-29 00:18:59

标签: php mysql

table1中有3列:book,key和value。

| book |   key    |  value   |    
------------------------------             
|  1   |  author  |    a     |              
|  1   |  editor  |    b     |        
|  1   |  book    |    c     |      

而不是运行三个查询

$data = mysql_query("
      SELECT * FROM table1 WHERE book = '1' AND key = 'author'
             ")  or die(mysql_error());  

while($info = mysql_fetch_array( $data ))
  {
       $value1 = $info['value'];
  }

然后对编辑和书籍重复此操作。

$ value1 $ value2 $ value3将插入页面上的不同位置

我可以使用一个查询执行此操作吗?

3 个答案:

答案 0 :(得分:1)

是。如果没有其他条目带有“book = 1”,您只需查询

SELECT * FROM table1 WHERE book = '1'

如果有更多条目,您可以使用此查询:

SELECT * FROM table1 WHERE book = '1' AND key IN('author','editor','book')

然后创建一个关联数组:

while($info = mysqli_fetch_assoc( $data ))
  {
       $value[$info['key']] = $info['value'];
  }

...

echo "the book {$value['book']} was written by {$value['author']}";

答案 1 :(得分:0)

要创建一个$ value数组,你必须使用它:

$value[] = $info['value'];

而不是:

$value1 = $info['value'];

:您可以使用此代码:

$value[]["key"] = $info['key'];
$value[]["value"] = $info['value'];

例如,您可以使用$value[0]["value"]

调用第一行的值

答案 2 :(得分:0)

如果您想要单个记录中的值,请尝试:

SELECT `t1`.`value` AS `value1`, `t2`.`value` AS `value2`, `t3`.`value` AS `value3`
FROM
    `table1` AS `t1` CROSS JOIN
    `table1` AS `t2` CROSS JOIN
    `table1` AS `t3`
WHERE
    (`t1`.`book` = 1) AND (`t1`.`key` = 'author')
    AND (`t2`.`book` = 1) AND (`t2`.`key` = 'editor')
    AND (`t3`.`book` = 1) AND (`t3`.`key` = 'book');