문제

Tables are usually laid out in a "horizontal" fashion:

+-----+----+----+--------+
|recID|FirstName|LastName|
+-----+----+----+--------+
|  1  |  Jim    | Jones  |
+-----+----+----+--------+ 
|  2  |  Adam   | Smith  |
+-----+----+----+--------+ 

Here, however, is a table with the same data in a "vertical" layout:

+-----+-----+----+-----+-------+
|rowID|recID| Property | Value |
+-----+-----+----+-----+-------+
|  1  |  1  |FirstName | Jim   | \
+-----+-----+----+-----+-------+  These two rows constitute a single logical record
|  2  |  1  |LastName  | Jones | / 
+-----+-----+----+-----+-------+
|  3  |  2  |FirstName | Adam  | \
+-----+-----+----+-----+-------+ These two rows are another single logical record
|  4  |  2  |LastName  | Smith | /
+-----+-----+----+-----+-------+

Question: In SQLite, how can I search the vertical table efficiently and in such a way that recIDs are not duplicated in the result set? That is, if multiple matches are found with the same recID, only one (any one) is returned?

Example (incorrect):

SELECT rowID from items WHERE "Value" LIKE "J%"

returns of course two rows with the same recID:

1 (Jim)
2 (Jones)

What is the optimal solution here? I can imagine storing intermediate results in a temp table, but hoping for a more efficient way.

(I need to search through all properties, so the SELECT cannot be restricted with e.g. "Property" = "FirstName". The database is maintained by a third-party product; I suppose the design makes sense because the number of property fields is variable.)

도움이 되었습니까?

해결책

To avoid duplicate rows in the result returned by a SELECT, use DISTINCT:

SELECT DISTINCT recID
FROM items
WHERE "Value" LIKE 'J%'

However, this works only for the values that are actually returned, and only for entire result rows.

In the general case, to return one result record for each group of table records, use GROUP BY to create such groups. For any column that does not appear in the GROUP BY clause, you then have to choose which rowID in the group to return; here we use MIN:

SELECT MIN(rowID)
FROM items
WHERE "Value" LIKE 'J%'
GROUP BY recID

To make this query more efficient, create an index on the recID column.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top