我已经为下面的描述提出了一个复杂的SQL语句。 所以我解释了3个表
客户
太一
CONF
所以查询是。我想为 [client.booked = 1] 中预订的客户选择所有记录以及 Accom 或中的相应记录conf 或用户提供的签入和结帐时间戳之间。
这就是我所拥有的。
"SELECT `client_id` FROM `accomm` WHERE `checkin` >= $fro AND `checkout` <= $to"
"SELECT `client_id` FROM `conf` WHERE `checkin` >= $fro AND `checkout` <= $to"
显然,这会选择所提供的签入和结帐之间的所有client_id,但不会过滤客户中已预订值的ID = 1
答案 0 :(得分:2)
我不会说这太复杂了:
SELECT DISTINCT c.*
FROM client c
LEFT JOIN accom a
ON a.client_id = c.client_id
AND a.checkin BETWEEN $from AND $to
LEFT JOIN conf co
ON co.client_id = c.client_id
AND co.checkin BETWEEN $from AND $to
WHERE c.booked = 1
AND a.client_id IS NOT NULL OR co.client_id IS NOT NULL
这假设您只需要客户端记录而不需要重复。
答案 1 :(得分:0)
SELECT c.*
FROM client c
WHERE c.booked = 1
AND (
EXISTS (SELECT 1
FROM accom a
WHERE a.client_id = c.client_id
AND a.checkin BETWEEN $from AND $to
)
OR
EXISTS (SELECT 1
FROM conf co
WHERE co.client_id = c.client_id
AND co.checkin BETWEEN $from AND $to
)
)
为了获得更好的性能,请创建以下索引:
答案 2 :(得分:0)
SELECT Client.client_id, name, email, facility_type, facility_id, checkin, checkout
FROM Client INNER JOIN (
SELECT 'Accom' AS facility_type, accom_id AS facility_id, client_id, checkin, checkout
FROM Accom
UNION
SELECT 'Conf' AS facility_type, conf_id AS facility_id, client_id, checkin, checkout
FROM Conf
) AS sub
ON Client.client_id = sub.client_id
WHERE booked = 1 AND checkin >= $from AND checkout <= $to;