我试图分散预订系统中的以下信息:
我有两个包含必要信息的表:产品表和预订表。没有任何预订的用户在预订表中没有记录;只有在预订所有产品的时间超过一年前,才能选择预订用户。
我有以下两个语句,但我想将它组合起来并且它们没有给我正确的信息(不幸的是我对这些困难的SQL语句不是很熟悉):
没有预订的用户(我认为这是正确的):
SELECT products.user_id, products.id
FROM products
LEFT JOIN bookings
ON bookings.product_id = products.id
WHERE bookings.product_id IS NULL
过去一年没有任何预订的用户(我选择了status_paid,它具有日期时间格式)
SELECT DISTINCT bookings.user_id, DATE_FORMAT(bookings.status_paid, '%Y-%m-%d')
FROM bookings
WHERE bookings.user_id NOT IN (
SELECT bookings.user_id
FROM bookings
WHERE DATE_FORMAT(bookings.status_paid, '%Y-%m-%d') >
DATE_ADD(DATE_FORMAT(bookings.status_paid, '%Y-%m-%d'), INTERVAL -1 YEAR)
)
AND bookings.status_paid IS NOT NULL
如何将它们组合起来并使它们起作用?
非常感谢帮助我!
答案 0 :(得分:0)
如果您需要简单连接,可以在两个选择之间使用左连接
select t1.user_id, t1.id
from (
SELECT products.user_id , products.id
FROM products
LEFT JOIN bookings
ON bookings.product_id = products.id
WHERE bookings.product_id IS NULL
) t1
left join (
SELECT DISTINCT bookings.user_id, DATE_FORMAT(bookings.status_paid, '%Y-%m-%d')
FROM bookings
WHERE bookings.user_id NOT IN (
SELECT bookings.user_id
FROM bookings
WHERE DATE_FORMAT(bookings.status_paid, '%Y-%m-%d') >
DATE_ADD(DATE_FORMAT(bookings.status_paid, '%Y-%m-%d'), INTERVAL -1 YEAR)
)
) t2 on t1.user_id = t2.user_id