1

我有那部分代码并想构建一个动态 SQL 语句:

//Build IN Clause
$sql_IN="'".implode("','", $keywords)."'";

//Build COUNT Clause
//tbd

//Get Clicks from YOURLS LOG
$sql_get_clicks="
                    SELECT 
                        count(case when shorturl ='u0lg' then 1 end) u0lg, 
                        count(case when shorturl ='3a8h' then 1 end) 3a8h,  
                        count(case when shorturl ='abcd' then 1 end) abcd,  
                        DATE_FORMAT((click_time),'%d.%m.%Y') Datum
                    FROM 
                        `yourls_log` 
                    WHERE  
                         DATE(click_time) BETWEEN '20170102' AND '20170104' AND
                         shorturl IN (".$sql_IN.")
                    Group By Datum";

该变量$keywords是一个带有关键字的数组。关键字在 IN 子句中使用,也必须在“count case 部分”中使用。$keywords 数组中的关键字数量是可变的。有什么技巧可以让我count(case..以简单而良好的编程风格构建它吗?

4

1 回答 1

1

您可以迭代$keywords数组并将每个值放入您在etc之后SELECT和之前附加的子句中。FROM

$keywords = array("foo", "bar", "baz");
$inClause = "'".implode("','", $keywords)."'";
$sql = "SELECT ";
foreach($keywords as $key) {
  $sql.="count(case when shorturl = '".$key."' then 1 end) ".$key.", ";    
}
$sql=rtrim($sql, ", ")." ";
$sql.= "FROM `your_logs` 
  WHERE 
    DATE(click_time) BETWEEN '20170102' AND '20170104' AND
    shorturl IN (".$inClause.")
    Group By Datum";

其中 avar_dump($sql);给出:

string(301) "SELECT count(shorturl = 'foo' 然后 1 end 的情况) foo, count(shorturl = 'bar' 然后 1 end 的情况) bar, count(shorturl = 'baz' 然后 1 end 的情况) baz , FROM your_logs WHERE DATE(click_time) BETWEEN '20170102' AND '20170104' AND shorturl IN ('foo','bar','baz') Group By Datum"

关于编程风格 - 您绝对应该查看准备好的语句

于 2017-01-04T14:42:15.993 回答