Customers Holidays id | name customer_id | start | end ---+------ ------------+--------+------ 1 | Peter 1 | 5 | 10 2 | Simon 1 | 15 | 20 3 | Mary 2 | 5 | 20
什麼是工作SQL查詢,可以給我所有客戶沒有特定日期的假期? 例如日期= 12如何執行刪除值的聯接?
- 彼得
- 瑪麗
這甚至與管理一個簡單的SQL連接,或者我需要使用子查詢?
Customers Holidays id | name customer_id | start | end ---+------ ------------+--------+------ 1 | Peter 1 | 5 | 10 2 | Simon 1 | 15 | 20 3 | Mary 2 | 5 | 20
什麼是工作SQL查詢,可以給我所有客戶沒有特定日期的假期? 例如日期= 12如何執行刪除值的聯接?
這甚至與管理一個簡單的SQL連接,或者我需要使用子查詢?
首先創建一個找到你想要什麼相反的查詢:誰做的客戶有對特定日期的節日:
SELECT DISTINCT name
FROM Customers
JOIN Holidays
ON id = customer_id
WHERE start <= 12 AND end >= 12
結果:
Simon
然後將此結果返回給客戶表並選擇加入失敗的結果:
SELECT name
FROM Customers
LEFT JOIN (
SELECT DISTINCT id
FROM Customers
JOIN Holidays
ON id = customer_id
WHERE start <= 12 AND end >= 12
) AS T1
ON Customers.id = T1.id
WHERE T1.id IS NULL
結果:
Peter
Mary
注意一個JOIN是不是這裏的唯一選擇。您也可以使用NOT EXISTS
,NOT IN
或EXCEPT
。由於您沒有指定哪個數據庫,因此我選擇了JOIN,因爲它是在所有主要關係數據庫中執行此操作的便捷高效方式。
我使用的測試數據(從問題中獲取):
CREATE TABLE Holidays (customer_id INT NOT NULL, start INT NOT NULL, end INT NOT NULL);
INSERT INTO Holidays (customer_id, start, end) VALUES
(1, 5, 10),
(1, 15, 20),
(2, 5, 20);
CREATE TABLE Customers (id INT NOT NULL, name NVARCHAR(100) NOT NULL);
INSERT INTO Customers (id, name) VALUES
(1, 'Peter'),
(2, 'Simon'),
(3, 'Mary');
SQLite,如果你想知道,但未來可能會改變。 * LEFT JOIN *和* IS NULL *是一個巧妙的技巧,沒有想到那個。 – 2010-04-06 18:35:12
我不認爲你想要「刪除」任何東西,只要選擇重疊你的開始/結束值的值,對吧?試試這個
SELECT
Name
FROM
Customers c
JOIN Holidays h on h.Customer_id = c.ID
WHERE
Start >= @Start
OR End <= @End
我認爲你正在尋找這樣的:
declare @myStart int
declare @myEnd int
SET @myStart = 11
SET @myEnd = 14
SELECT c.name
FROM Customers c
INNER JOIN Holidays h
ON c.id=h.customer_id
WHERE
(@myStart BETWEEN h.start AND h.end) OR
(@myEnd BETWEEN h.start AND h.end) OR
(@myStart < h.start AND @myEnd > h.end)
select
c.name
from
Customers c
left outer join
Holidays h
on
h.customer_id=c.id
where
h.start <= 11
and
h.end >= 14
group by
c.id
你可以這樣做
-- Get customers only from Customers table
SELECT name FROM Customers
WHERE id NOT IN (-- Get the intersection between the two tables
SELECT id FROM Customers JOIN
Holidays ON Customers.Id = Holidays.customer_id
WHERE Holidays.start=12 AND Holidays.end = 12)
你能說清楚你的意思嗎「out of * start = 11,end = 14 *?那部分對我來說很模糊這應該會影響你的查詢。你是說開始和結束之間的範圍與範圍11-14(在你的例子中)重疊? – Jaxidian 2010-04-06 18:06:50