具有重复键时选择指定的值

时间:2013-10-27 12:26:18

标签: sql duplicates identifier

所以我有一张桌子,例如租来的物品

 id | itemID | state
 3  |      2 |     0
 2  |      2 |     1
 1  |      2 |     1

状态表示项目是否在过去租用。 0 = currently rented

表项目:

id | item   | condition
1  | showel |      good
2  |    saw |        ok

现在我想选择目前没有租用的物品,我最终得到了这个:

SELECT * FROM
(
  SELECT CASE WHEN b.itemID = a.id AND b.state = 0 THEN 1
  ELSE 0 END AS itemState, a.condition AS condition
  FROM items AS a
  LEFT JOIN rented AS b ON a.id = b.item_id
) AS states
WHERE states.itemState = 0

但是SQL返回时看到[id = 2]目前是免费的,但事实并非如此。

有没有办法修复SQL语句?

//编辑:我需要在租借的表中保留重复的itemID

1 个答案:

答案 0 :(得分:0)

如果我理解你所追求的是什么,你可以这样做:

SELECT outerA.*
  FROM items AS outerA
    LEFT JOIN (SELECT innerA.*
                 FROM rented AS innerA
                   JOIN (SELECT MAX(id) AS id 
                           FROM rented 
                           GROUP BY itemID) AS innerB
                     ON innerB.id = innerA.id) AS outerB
      ON outerB.itemID = outerA.id
  WHERE outerB.state IS NULL
    OR outerB.state = 1;

它将选择任何从未租用的项目或rented表中的最后一项表示当前未租用的项目。

另请参阅此 short demo