SQLite:如何搜索多个值?

时间:2016-09-29 14:36:53

标签: android sql sqlite android-sqlite

我的表col1,col2,col3中有两个autocomplettextview和3列。 col1是主键

表格如下:

| col1 | col2   |  col3                 |
-----------------------------------------
| 1    | store1 |apple,pineapple,mango  |
| 2    | store2 | apple,orange          |
| 3    | store3 | apple,pineapple,orange|
| 4    | store4 | orange,mango          |
| 5    | store5 | mango,jackfruit       |

我有两个问题:

Q1 :我可以在单列中存储多个值。如果没有,那么我该如何存储?

Q2 :之前说我有两个autocompletetextview来搜索

即:

如果用户在两个autocompletetextview 中键入apple和pineapple,那么我需要 显示与这两个文本匹配的行。

预期o / p

| col1 | col2   |  col3                 |
-----------------------------------------
| 1    | store1 |apple,pineapple,mango  |
| 2    | store3 | apple,pineapple,orange|

我怎样才能做到这一点?

我在foreign key的帮助下经历了几次研究,我可以在单列中存储多个值,但是如何在Where clause中使用外键来实现{ {1}}。

1 个答案:

答案 0 :(得分:1)

您不应在同一列中存储多个值。相反,你应该使用三个表。

然后很容易找到StoreID有两种食物

SELECT FoodAvailable.StoreID
FROM FoodAvailable
JOIN Foods
  ON FoodAvailable.FoodID = Foods.FoodID
WHERE Foods.Food in ('apple', 'pineapple')
GROUP BY FoodAvailable.StoreID
HAVING count(*) = 2

商品

| StoreID | StoreName |
-----------------------
| 1       | store1    |
| 2       | store2    |
| 3       | store3    |
| 4       | store4    |
| 5       | store5    |

<强>食品

| FoodID  | Food      | 
-----------------------
| 1       | apple     |
| 2       | pineapple |
| 3       | mango     |
| 4       | orange    |
| 5       | jackfruit |

<强> FoodAvailable

| StoreID | FoodID | 
---------------------
| 1       | 1      | //apple 
| 1       | 2      | //pineapple
| 1       | 3      | //mango  
| 2       | 1      | //apple 
| 2       | 4      | //orange
| 3       | 1      | //apple 
| 3       | 2      | //pineapple
| 3       | 4      | //orange
| 4       | 4      | //orange
| 4       | 3      | //mango  
| 5       | 3      | //mango  
| 5       | 5      | //jackfruit

您的最终查询是这样的

SELECT f.StoreID, GROUP_CONCAT(food ORDER BY food DESC SEPARATOR ', ')
FROM FoodAvailable f
WHERE f.StoreID = (SELECT FoodAvailable.StoreID
                   FROM FoodAvailable
                   JOIN Foods
                     ON FoodAvailable.FoodID = Foods.FoodID
                   WHERE Foods.Food in ('apple', 'pineapple')
                   GROUP BY FoodAvailable.StoreID
                   HAVING count(*) = 2
                  )
GROUP BY f.StoreID