简体   繁体   English

select 项目,其中 id 包含在另一个表字段中

[英]select items where id is contained in another table field

I have the following database schema in sqlite3:我在 sqlite3 中有以下数据库架构:

在此处输入图像描述

Basically, a member has multiple characters.基本上,一个成员有多个字符。 A character plays in an activity (with a mode type) and has results for that activity (character_activity_stats)一个角色在一个活动中玩耍(具有模式类型)并具有该活动的结果(character_activity_stats)

I select all of the stats (activity / character_activity_stats) for a specific character and mode like so:我 select 特定角色和模式的所有统计信息(活动 / character_activity_stats),如下所示:

SELECT
*,
activity.mode as activity_mode,
character_activity_stats.id as character_activity_stats_index
FROM
    character_activity_stats

INNER JOIN
    activity ON character_activity_stats.activity = activity.id,
    modes ON modes.activity = activity.id

WHERE
    modes.mode = 5 AND
    character_activity_stats.character = 1

This works great.这很好用。

However, now I want to select the same set of data, but by member (basically combine results for all characters for a member).但是,现在我想 select 同一组数据,但是按成员(基本上将所有字符的结果组合为一个成员)。

However, I am not really sure how to even approach this.但是,我什至不确定如何处理这个问题。

Basically, I need to retrieve all character_activity_stats where character_activity_stats.character is a character of the specified member (by id).基本上,我需要检索所有 character_activity_stats 其中 character_activity_stats.character 是指定成员的字符(按 id)。 Any suggestions or pointers?有什么建议或指示吗? (I am very new to sql). (我对 sql 很陌生)。

Join those 3 tables on the right keys:加入右键上的这 3 个表:

select *
from character_activity_stats
join character on character_activity_stats.character = character.id
join member on member.id = character.member
where member.id = ?

If you don't need any data from member other than limit by id, then you leave that join off and just do character.member =?如果除了 id 限制之外您不需要来自成员的任何数据,那么您可以关闭该连接并执行 character.member =? instead.反而。

It's much easier if you use the same name for the primary and foreign keys (ie don't use id for the primary key).如果您对主键和外键使用相同的名称(即不要将 id 用于主键),则会容易得多。 It also allows you use natural joins so you don't even need to give the join conditions.它还允许您使用自然连接,因此您甚至不需要提供连接条件。 For the primary key to convention is usually _id.对于约定的主键通常是_id。 You id and _in in most of the tables, so I don't what is that is about.您在大多数表格中都有 id 和 _in,所以我不知道那是什么意思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM