我有一个问题:
SELECT
MAX(date),
logId,
computerId
FROM
logTable
WHERE logId IN ('1','2','3')
但是我想要IN子句测试computerId就像这样:
logId ='1'和 computerId ='998874',
logId ='2'和 computerId ='334211', ...
怎么做?
答案 0 :(得分:2)
您必须将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
答案 1 :(得分:1)
我认为你不能用IN
条款做到这一点。我认为你需要一个有条件的地方。所以:
SELECT MAX(date), logId, computerId
FROM logTable
WHERE (logId = 1 AND computerId = '998874') OR
(logId = 2 AND computerId = '334211') OR
...
答案 2 :(得分:1)
IN
不支持元组。您可以使用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
答案 3 :(得分:0)
像这样:
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