按复合索引查询SQL

时间:2014-04-23 14:09:10

标签: sql postgresql

我们假设我有一个itemsid type number roomid是主键, (type, number)是一个独特的复合键;列inventoryiditem_typeitem_numberowner的表格id是主键,(type, number)是独特的复合键。

示例:

items

| id | type    | number | room |
+----+---------+--------+------+
|  1 |  laptop |      1 |   12 |
|  2 |  laptop |      2 |   13 |
|  3 | desktop |      1 |   13 |

inventory

| id | item_type | item_number | owner |
+----+-----------+-------------+-------+
|  1 |    laptop |           1 |   Joe |
|  2 |    laptop |           2 |   Joe |
|  3 |   desktop |           1 | Susan |

如何查询Joe拥有的所有items?如果我做

SELECT *
FROM items
WHERE (type, number) IN (
    SELECT item_type, item_number FROM inventory WHERE owner = 'Joe'
)

我只在结果中获得一行,但子查询返回多行。我似乎无法在多列上执行join,例如

SELECT *
FROM items
JOIN inventory ON inventory.item_type = items.type,
    inventory.item_number = items.number`
WHERE inventory.owner = 'Joe'

1 个答案:

答案 0 :(得分:4)

您应该将连接条件与AND组合,而不是用逗号组合。