如果未找到第二个表行,如何显示第一行请参见示例 感谢
$result1 = mysql_query("
SELECT a.user_name
, a.date
, a.checkin
, o.checkout
FROM attend a
LEFT
JOIN attendout o
ON a.user_name = o.user_name
AND a.date = o.date
WHERE a.date BETWEEN '2015-06-01' AND '2015-06-09'
AND o.user_name = 'salman';
");
现在显示如下
username date checkin checkout
salman 2015-06-01 11:31:34 17:23:47
salman 2015-06-02 11:19:23 17:15:15
salman 2015-06-03 11:48:22 18:16:27
salman 2015-06-06 11:39:26 16:56:13
salman 2015-06-07 11:24:59 17:36:01
我想要这样
username date checkin checkout
salman 2015-06-01 11:31:34 17:23:47
salman 2015-06-02 11:19:23 17:15:15
salman 2015-06-03 11:48:22 18:16:27
salman 2015-06-06 11:39:26 16:56:13
salman 2015-06-07 11:24:59 17:36:01
salman 2015-06-08 12:24:59
salman 2015-06-09 10:24:59
因为某些时间结帐行为空
答案 0 :(得分:1)
将 second 表格中的条件从WHERE
移至ON
:
SELECT a.user_name, a.date, a.checkin, o.checkout
FROM attend a LEFT JOIN
attendout o
ON a.user_name = o.user_name AND
a.date = o.date AND o.user_name = 'salman'
WHERE a.date BETWEEN '2015-06-01' AND '2015-06-09' ;
当您将条件放在WHERE
子句中时,您将LEFT JOIN
变为INNER JOIN
,因为NULL
值被滤除了。
答案 1 :(得分:0)
为结帐列添加条件:
SELECT attend.user_name,attend.date,attend.checkin, attendout.checkout
FROM attend
left join attendout on attend.user_name=attendout.user_name AND attend.date=attendout.date
WHERE attend.date BETWEEN '2015-06-01'
AND '2015-06-09'
AND attendout.user_name='salman'
AND attendout.checkout IS NOT NULL
或使用!=运算符,如果值可以为空
完整代码: 如果你没有任何记录,将LEFT JOIN替换为INNER JOIN将对你有用
$result1 = mysql_query("
SELECT a.user_name
, a.date
, a.checkin
, o.checkout
FROM attend a
JOIN attendout o
ON a.user_name = o.user_name
AND a.date = o.date
WHERE a.date BETWEEN '2015-06-01' AND '2015-06-09'
AND o.user_name = 'salman';
");
否则使用:
$result1 = mysql_query("
SELECT a.user_name
, a.date
, a.checkin
, o.checkout
FROM attend a
LEFT JOIN attendout o
ON a.user_name = o.user_name
AND a.date = o.date
WHERE a.date BETWEEN '2015-06-01' AND '2015-06-09'
AND o.user_name = 'salman'
AND o.checkout != ''
AND o.checkout IS NOT NULL;
");