我正在使用Postgresql来查询数据。
我所做的如下:
表1:
#id #zone_id #name #timestamp_create
1 1 Alex 2016-08-10 11:00:11.07+00
2 1 James 2016-08-10 11:30:11.07+00
3 1 Mary 2016-08-10 11:45:11.07+00
4 1 Ken 2016-08-10 12:15:11.07+00
5 1 Aston 2016-08-10 12:45:11.07+00
6 2 Tom 2016-08-11 11:28:11.07+00
7 2 Edward 2016-08-11 11:30:11.07+00
表2:
#id #zone_id #code #timestamp_start #timestamp_end
1 1 A 2016-08-10 10:50:11.07+00 2016-08-10 11:15:11.07+00
2 1 B 2016-08-10 11:16:11.07+00 2016-08-10 11:50:11.07+00
3 2 E 2016-08-11 10:30:11.07+00 2016-08-11 10:30:11.07+00
我的查询:
SELECT t1.zone_id, t1.name, t2.code, t1.timestamp_create
FROM table1 as t1 INNER JOIN table2 as t2 ON t1.zone_id = t2.zone_id
WHERE t1.timestamp_create BETWEEN t2.timestamp_start AND t2.timestamp_end
结果:
#zone_id #name #code #timestamp_create
1 Alex A 2016-08-10 11:00:11.07+00
1 James B 2016-08-10 11:30:11.07+00
1 Mary B 2016-08-10 11:45:11.07+00
如何实现以下结果:
#zone_id #name #code #timestamp_create
1 Alex A 2016-08-10 11:00:11.07+00
1 James B 2016-08-10 11:30:11.07+00
1 Mary B 2016-08-10 11:45:11.07+00
1 Ken 2016-08-10 12:15:11.07+00
1 Aston 2016-08-10 12:45:11.07+00
我也试过使用LEFT OUTER JOIN,但它仍然不起作用。
任何建议都表示赞赏。
答案 0 :(得分:1)
只需切换到$array1 = [a,b,c,d];
$array2 = [word,word1,word2,word3];
$array3 = [3,4,6,7];
$tableStr = "<table>";
foreach ($array1 as $key => $array1Value) {
$tableStr .= "<tr><td>".$array1Value.'</td><td>'.$array2[$key].'<td></td>'.$array3[$key].'</td></tr>';
}
$tableStr .= "</table>";
echo $tableStr;
即可,因为您left join
中的条件涉及右表的列。对于不匹配的行,这些列将包含where
,因此他们不会满足条件。
要实现您的目标,请切换到null
并将该条件移至left join
子句
on
答案 1 :(得分:0)
您需要left join
,但必须将条件移至on
子句:
SELECT t1.zone_id, t1.name, t2.code, t1.timestamp_create
FROM table1 t1 LEFT JOIN
table2 t2
ON t1.zone_id = t2.zone_id AND
t1.timestamp_create BETWEEN t2.timestamp_start AND t2.timestamp_end