[英]SQLITE3: converting IDs to codes when there are hundreds of columns to convert
I have a table A that has several hundred columns (let's say 301 for example) with the first column being the primary key and the rest being IDs from table B ie 我有一个表A,它有几百列(比如说301),第一列是主键,其余是表B的ID,即
CREATE TABLE "A" (
ko_index_id INTEGER NOT NULL,
ko1 INTEGER NOT NULL,
ko2 INTEGER NOT NULL,
...
ko300 INTEGER NOT NULL,
PRIMARY KEY (ko_index_id)
);
CREATE TABLE "B" (
id INTEGER NOT NULL,
name INTEGER NOT NULL,
PRIMARY KEY (id)
);
I would like to be able to convert the IDs into names. 我希望能够将ID转换为名称。 For example: 例如:
SELECT name FROM B WHERE id in (SELECT * FROM A);
Except the SELECT *
part means that ko_index_id will be fed into B
which is wrong. 除了SELECT *
部分,这意味着ko_index_id将被馈送到B
,这是错误的。 If there were only two columns in A
I could just write 如果A
中只有两列,我可以写
SELECT name FROM B WHERE id in (SELECT ko1, ko2 FROM A);
but table A
has 300 columns! 但是表A
有300列!
Can anyone help me around this? 有人可以帮我解决这个问题吗?
I agree with @Gordon's comment. 我同意@Gordon的评论。 If you can afford to change your data model, I would suggest you use an intersection table. 如果您有能力更改数据模型,建议您使用一个交叉表。 It's the typical way to model "many-to-many" relationships in a database. 这是在数据库中建模“多对多”关系的典型方法。
Example: 例:
CREATE TABLE "A" (
id INTEGER NOT NULL,
...
PRIMARY KEY (id)
);
CREATE TABLE "B" (
id INTEGER NOT NULL,
name INTEGER NOT NULL,
...
PRIMARY KEY (id)
);
CREATE TABLE "AB" (
a_id INTEGER NOT NULL,
b_id INTEGER NOT NULL
);
SELECT A.id, B.name
FROM A
INNER JOIN AB ON A.id=AB.a_id
INNER JOIN B ON AB.b_id=B.id;
300+ columns? 300列以上? How about redoing table A
by pivoting those columns into rows. 通过将这些列旋转到行中来重做table A
You could have key name and value column. 您可能有键名称和值列。 For example: 例如:
select * from A:
id, ko_name, ko_value
1, ko1, 5
1, ko2, 6
Then selecting the keys becomes much easier; 然后选择键变得容易得多。 eg: 例如:
SELECT name FROM B WHERE id in (SELECT ko_value FROM A where ko_name in ('ko1', 'ko2')) ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.