我有一个查询:
SELECT
MAX(date),
logId,
computerId
FROM
logTable
WHERE logId IN ('1','2','3')
但是我希望IN子句也像这样测试computerId:
logId = ' 1 ' 和 computerId =‘998874’,
logId = '2' and 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
我不认为你可以这样做与IN
条款。我觉得你需要一个有条件的位置。所以:
SELECT MAX(date), logId, computerId
FROM logTable
WHERE (logId = 1 AND computerId = '998874') OR
(logId = 2 AND computerId = '334211') OR
...
SQL Server中的IN
不支持元组。您可以使用EXISTS
和表表达式。
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