最小化在同一个表Mysql上的选择查询

时间:2012-06-01 17:03:27

标签: php mysql database select

我一直试图弄清楚如何将这些 php-mysql 查询减少到最低限度。我想写一个可以获取所有数据的单个查询。


$db_u = mysql_fetch_array(mysql_query("SELECT * FROM u_settings WHERE setting='username'"));
$db_p = mysql_fetch_array(mysql_query("SELECT * FROM u_settings WHERE setting='password'"));
$db_e = mysql_fetch_array(mysql_query("SELECT * FROM u_settings WHERE setting='email'"));
$db_t = mysql_fetch_array(mysql_query("SELECT * FROM u_settings WHERE setting='tag'"));
$db_a = mysql_fetch_array(mysql_query("SELECT * FROM u_settings WHERE setting='active'"));
$db_v = mysql_fetch_array(mysql_query("SELECT * FROM u_settings WHERE setting='version'"));
$db_ti = mysql_fetch_array(mysql_query("SELECT * FROM u_settings WHERE setting='time'"));
$db_wa = mysql_fetch_array(mysql_query("SELECT * FROM u_settings WHERE setting='warn'"));
$data_dis = mysql_fetch_array(mysql_query("SELECT * FROM u_settings WHERE setting='dis'"));

上面做的就是让Ram陷入困境。任何帮助表示赞赏。

检查其他问题不适合该法案。

3 个答案:

答案 0 :(得分:3)

尝试 IN 而不是那么多查询

 SELECT * FROM u_settings WHERE setting IN ('username', 'password','email','tag','active','version','time','warn','dis');

答案 1 :(得分:2)

是的,编写一个没有WHERE子句的SELECT查询。这将从表中获取所有信息。

答案 2 :(得分:0)

如果你想保留每个变量,你可以创建一个数组并按这样做。

$keys = array(
'db_u' => 'username',
'db_p' => 'password',
'db_t' => 'tag'
);

foreach($keys as $key => $value) {
    &$keys[$key] = mysql_fetch_array(mysql_query("SELECT * FROM u_settings WHERE setting='{$value}'"));
}

我没有检查代码,但我认为你明白了。它将每个结果存储在一个数组中。

这可能是一种更简单的方法。