我设置了以下表格:
MEMBERS
_________________________________________________
|memberid | firstname | lastname | sessions|
_________________________________________________
|1 | john | doe | 1 |
|2 | Dave | Smith | 2 |
_________________________________________________
BOOKINGS
___________________________________
|id |memberid | date | time | group |
___________________________________
|1 |1 |2016-04-19 | 08:00 | 1 |
|2 |2 |2016-04-18 | 13:00 | 4 |
|3 |1 |2016-04-15 | 18:00 | 3 |
_______________________________________________
我想在本周的预订表中返回所有成员的名字和姓氏。
我有php代码来生成两个日期
$ FirstDay =日期(" Y-m-d",strtotime('上周日'));
<$> $ LastDay = date(&#34; Y-m-d&#34;,strtotime(&#39;本周星期日&#39;));替换为where子句=其中bookings.date介于&#39; $ FirstDay&#39;和#LastDay&#39;
非常感谢任何帮助!
答案 0 :(得分:1)
这应该做的工作:
SELECT firstname, lastname, sessions, count(bookings.id) AS sum_bookings
FROM members
JOIN bookings ON bookings.memberid = members.memberid
WHERE date BETWEEN ? AND ?
GROUP BY members.memberid
HAVING sessions > sum_bookings
详细了解BETWEEN
here
或使用您的变量:
$query = "SELECT firstname, lastname, sessions, count(bookings.id) AS sum_bookings
FROM members
JOIN bookings ON bookings.memberid = members.memberid
WHERE date BETWEEN '".$FirstDay."' AND '".$LastDay."'
GROUP BY members.memberid
HAVING sessions > sum_bookings";
小心插入这样的变量。它可能使您容易受到SQL注入攻击,最好使用prepared statements