我有这样的mysql表:
Name1 Name2 Name3 Name4 date
----------
Rachel John Sebastian Luk 2015-07-20 18:20:13
Stephan Luk Michele Steve 2015-06-20 18:20:13
Rachel John Sebastian Luk 2015-09-20 18:20:13
Stephan Luk Michele Steve 2015-03-20 18:20:13
Rachel John Sebastian Luk 2014-07-20 18:20:13
Stephan Luk Michele Steve 2015-03-20 18:20:13
Rachel John Sebastian Luk 2015-05-20 18:20:13
Stephan Luk Michele Steve 2015-02-20 18:20:13
我有这样的数组:$names = ["Luk","Steve","Ingrid"]
我需要为每个数组的名称选择最近的行,其中名称存在。
我目前的代码是:
foreach ($names as $n){
$sql = "SELECT date FROM dbtable
WHERE name1='".$n."' OR name2='".$n."' OR name3='".$n."' OR
name4='".$n."' ORDER BY date DESC LIMIT 1";
$result = $con->query($sql);
$row = mysqli_fetch_array($result, MYSQL_ASSOC);
$date[$n] = $row['date'];
}
它工作正常,但是当数组$ names和mysql表变大时,它变慢了。也许有一种方法可以减少对数据库或更好查询的请求?
答案 0 :(得分:1)
您可以将其作为一个mysql查询。但我不确定它不需要太多资源。
如果表t1具有(Name1,Name2,Name3,Name4,date1)
Create Temporary table t2 (Name0 text);
Insert into t2 values ('Luk'), ('Steve'), ('Ingrid');
Select t2.Name0, max(t1.date1) maxtime from t1,t2 where t2.Name0 in (t1.Name1, t1.Name2, t1.Name3, t1.Name4) group by name0
结果
Name0 maxtime
Luk 2015-09-20 18:20:13
Steve 2015-06-20 18:20:13