2014-01-22 75 views
1

我有两个表,路线和用户。每条路由都有一个整数ID,每个用户都有一个逗号分隔的路由列表,他们可以访问。我试图从路由表中选择那些行,其id位于用户行的id列表中。sqlite3:我想根据不同表中的ID列表选择行

查询(至少我是怎么想的,应该形成),我尝试使用是一样的东西

select * 
from routes 
where id in (select allowed_ids 
      from users 
      where username = 'sameple'); 

路由表的格式为

id, name 
0, 'test name' 
2, 'test name' 
3, 'test name' 

用户表格式为

id, name, username, password, allowed_ids 
0, 'name', 'uname', 'md5pw', '0, 3' 

问题是,这是行不通的。有没有更好的方法或做到这一点?

我对SQL很陌生,所以任何帮助都非常感谢!

+0

你的问题是什么?你使用的是子查询,它是一个基于来自其他表的值得到来自一个表的结果的有效选项。 – 2014-01-22 21:14:45

+0

您会发现在这里使用连接会很有用。 – squiguy

+0

@squiguy好吧,怎么样? –

回答

1

我会创建第三个表,其中保存了用户ID和路径ID。

UserRoutes 
PrimaryKey->ID 
ForeignKey->UserID 
ForeignKey->RoutesKey 

Users 
PrimaryKey->ID 

Routes 
PrimaryKey->ID 

所以,你可以

SELECT * FROM UserRoutes, Routes WHERE UserRoutes.UserID = x; 

也觉得这标准的方式SQLite中。

0

使用join(假设allowed_ids是一个数组):

SELECT * 
FROM routes 
JOIN users 
ON id = ANY(users.allowed_ids) 
WHERE username = 'sample' 
+0

不幸的是,在sqlite3中没有数组。 –

+0

在这种情况下,我会建议戈登的答案。 – That1Guy

+0

谨慎解释downvote? – That1Guy

1

这是行不通的,但这样的可能:

select r.* 
from routes r 
where exists (select 1 
       from users u 
       where username = 'sameple' and 
        ', '||u.allowed_ids||', ' like '%, '||id||', %' 
      ); 

您也可以表达这种join,但这会保持你尝试的精神。

以逗号分隔的文本列存储事物列表不好想法。你应该有一个单独的表,每个用户有一行,allowed_id。

+0

不幸的是我无法得到这个工作。 –

+0

问题是什么? –

相关问题