如何使用php创建动态查询?

时间:2015-12-30 22:32:43

标签: php mysql arrays loops

我有一张这样的表:

// mytable
+----+---------+------------+
| id | id_post | code_table |
+----+---------+------------+
| 1  | 34523   | 1          |
| 2  | 3453    | 4          |
| 3  | 43434   | 2          |
| 4  | 54321   | 1          |
| 5  | NULL    | NULL       |
| 6  | 32411   | 2          |
| 7  | 42313   | 1          |
| 8  | 34242   | 2          |
+----+---------+------------+
//                    ^ all of my focus is on this column

我也有这个阵列:

$convert_code_name = array (
                        "1" => "Post1", 
                        "2" => "Post2", 
                        "3" => "Post3",
                        "4" => "Post4"  
                           );

现在我想创建

$query = "select * from post1
             union all
          select * from post2
             union all
          select * from post4";

          // there isn't "post3", because 3 isn't exist in the code_table column

我该怎么做?

这是我的尝试

// connect to database
$stm = $db->prepare('select * from mytable');
$stm->execute();
$result = $stm->fetch();

/* array_unique: removes duplicate values
   array_filter: removes "NULL" values */

array_filter(array_unique($result[code_table]), function($item) {
    return $item != 'NULL';
});

foreach($item as $numb){
    $query .= 'select * from'.$convert_code_name[$numb].'union all';
}

但我不知道为什么我的代码无法正常工作,我该怎么做?

3 个答案:

答案 0 :(得分:3)

首先,在查询中使用SELECT DISTINCT来获取唯一值,因此您无需调用array_unique

然后,一旦掌握了所有值,就可以使用implode将所有SELECT个查询与UNION ALL相关联。

$stm = $db->prepare("SELECT DISTINCT code_table FROM mytable WHERE code_table IS NOT NULL");
$stm->execute();
$results = $stm->fetchAll();
// This returns a 2-dimensional array, we just want one column
$results = array_column($results, 'code_table');

$query = implode(' UNION ALL ', array_map(function($code_table) use ($convert_code_name) {
    return "SELECT * FROM " . $convert_code_name[$code_table];
}, $results));

答案 1 :(得分:1)

$query .= 'select * from'.$convert_code_name[$numb].'union all';

将生成错误的sql,将其更改为(我假设$ convert_code_name [$ numb]包含完整的表名,如Post1,Post2):

$query = '';
foreach($item as $numb){
    $query .= ($query!=''?' union all ':'') . 'select * from '.$convert_code_name[$numb];
}

答案 2 :(得分:0)

您只需要先执行此查询:

G'

然后,您可以根据其结果构建第二个查询,该结果仅为每个现有SELECT DISTINCT code_table FROM events 包含1行。