离开加入获得最小日期

时间:2014-02-24 09:37:07

标签: php mysql

我想在我的数据库中获取每个预订的第一个日期。

表BOOKINGS就像:

id | id_client_booking | the_date

表CLIENT_BOOKINGS是

id | etc | etc
<{1>} BOOKINGS每个id_client_booking对应id CLIENT_BOOKINGSSELECT min(the_date) AS start_date, id_client_booking FROM `day_bookings`AS db LEFT JOIN `client_bookings`AS cb ON db.id_client_booking = cb.id ,并且可以有很多日期。

我希望获取每位客户预订的第一个日期。这个选择只给我所有客户预订的第一个日期。我错过了什么?

SELECT
min(the_date) AS db.start_date, db.id_client_booking
                 ^^             ^^
FROM `day_bookings`AS db
LEFT JOIN `client_bookings`AS cb ON db.id_client_booking = cb.id

也试过:

You have an error in your SQL syntax;

但错误:{{1}}

3 个答案:

答案 0 :(得分:1)

你错过了GROUP BY,试试这个:

SELECT MIN(the_date) AS start_date, id_client_booking
FROM `day_bookings`AS db
LEFT JOIN `client_bookings`AS cb 
ON db.id_client_booking = cb.id
GROUP BY id_client_booking

答案 1 :(得分:1)

您需要使用GROUP BY汇总功能才能使MIN()正常工作

SELECT min(the_date) AS start_date, id_client_booking
FROM `day_bookings` AS db
LEFT JOIN `client_bookings` AS cb 
ON db.id_client_booking = cb.id
GROUP BY db.id_client_booking

答案 2 :(得分:0)

您只能使用AS关键字来定义表达式或别名的名称 您不能使用它直接指向列。因此是语法错误。

SELECT
min(the_date) AS db.start_date, db.id_client_booking
                 ^^             ^^
FROM `day_bookings`AS db
LEFT JOIN `client_bookings`AS cb ON db.id_client_booking = cb.id

应该是:

SELECT
min(the_date) AS 'start_date', db.id_client_booking
FROM `day_bookings`AS db
LEFT JOIN `client_bookings`AS cb ON db.id_client_booking = cb.id