【问题标题】:How to select from multiple tables based on condition如何根据条件从多个表中进行选择
【发布时间】:2017-06-17 11:56:10
【问题描述】:

我有两张桌子:

张贴表:

+-----+------------+--------------+
| id  |   title    |   details    |
+-----+------------+--------------+
| 185 | some title | some details |
| 186 | some title | some details |
+-----+------------+--------------+

帖子类别:

+----+------------+---------+
| id |  category  | post_id |
+----+------------+---------+
|  1 | some title |     185 |
|  2 | some title |     186 |
+----+------------+---------+

当用户点击类别时,我想根据所选类别从post table 获取所有帖子。

我可以像这样选择categorypost_id

List<Map> postCategories2 = Base.findAll("select category, post_id from posts_categories where category = ?", request.queryParams("category_name"));

但我想要的是使用单个查询并使用表 2 中的 category and post_idpost table 中选择 id, title, details,即 category table

我拥有的所有信息都是类别名称,即request.queryParams("category_name")

注意:id and post_id 有主键-外键关系

【问题讨论】:

  • 提示:JOIN 将桌子放在一起。

标签: java sql activejdbc javalite


【解决方案1】:

我认为您必须为此使用连接 用此查询替换您的查询

select title,details,category from post p inner join posts_categories c on 
 p.id=c.post_id where category= ?//your category name at the question mark

希望对你有帮助

【讨论】:

  • 我在帖子表中没有categoryposts_categories c 中的“c”是什么意思?
  • 我实际使用过 join 。 category 是列的名称,而 c 只是 posts_categories 表的对象,只是为了不一次又一次地写入该表的名称。我实际上已经从 post_categories 表中的 post 表和类别中获取了标题和详细信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多