我有一個查詢:在1和表2場第
SELECT
MAX(date),
logId,
computerId
FROM
logTable
WHERE logId IN ('1','2','3')
但我想IN子句測試computerId太像這樣:
LOGID = '1' 和 computerId = '998874',
LOGID = '2' 和 computerId = '334211', ...
如何做到這一點?
我有一個查詢:在1和表2場第
SELECT
MAX(date),
logId,
computerId
FROM
logTable
WHERE logId IN ('1','2','3')
但我想IN子句測試computerId太像這樣:
LOGID = '1' 和 computerId = '998874',
LOGID = '2' 和 computerId = '334211', ...
如何做到這一點?
你將不得不使用多個替換IN
聲明OR
聲明
SELECT MAX(date)
, logId
, computerId
FROM logTable
WHERE (logId = '1' AND computerid = '998874')
OR (logId = '2' AND computerid = '334211')
或者,如果你有很多的條件下,它可能是更具可讀性爲他們創建一個內存表,並在這些條件下加入
;WITH Conditions (logID, computerid) AS (
SELECT '1', '998874'
UNION ALL SELECT '2', '334211'
)
SELECT MAX(date)
, logId
, computerId
FROM logTable lt
INNER JOIN Conditions c ON c.logID = lt.LogID
AND c.computerid = lt.computerID
是比第一種更高性能的第二種方式嗎? – Florian
不確定,但可以肯定的是,你必須比較兩個選項。請注意,這種特殊情況下的性能差異並不明顯。 –
我不認爲你可以用IN
條款做到這一點。我認爲你需要一個有條件的地方。因此:
SELECT MAX(date), logId, computerId
FROM logTable
WHERE (logId = 1 AND computerId = '998874') OR
(logId = 2 AND computerId = '334211') OR
...
IN
SQL Server不支持元組。您可以使用EXISTS
和表格表達式。 2008語法如下。
SELECT MAX(l.date),
l.logId,
l.computerId
FROM logTable l
WHERE EXISTS(SELECT *
FROM (VALUES ('1', '998874'),
('2', '334211')) v(logId, computerId)
WHERE v.computerId = l.computerId
AND v.logId = l.logId)
GROUP BY l.logId,
l.computerId
像這樣:
SELECT
MAX(date),
logId,
computerId
FROM
logTable
WHERE (logId = '1' AND computerId = '998874')
OR (logId = '2' AND computerId = '334211')
OR (logId = '3' AND computerId = '123456')
GROUP BY logId, computerId
是否有特定的對,就像你的例子? OS如果logid ='1',那麼computerid必須等於'998874'並且僅'998874'? – Maess