SQL插入到表中,其中从其他表中选择的值匹配其他表

发布于 2025-01-29 07:29:35 字数 1431 浏览 5 评论 0原文

我有以下表:

table1

idRarity
1common
2罕见
3稀有

table2

idtype
1Air
2 Air 2Earth
3Earth 3 Fire
4

已经存在输出表和架构如下:

RarityIdfeekness_typeidustimance_typeid

,我应该根据表2和表1填充行。

例如,如果我给出:

  • 类型是'water'和'air'
  • rarity是'common'

我想添加table1中包含的ID表2到此表获取以下更新的输出表:

rarityIdfeekness_typeidustistance_typeid
141

我写了以下查询:

INSERT INTO table3 (rarityID, weakness_typeID, resistance_typeID)
    SELECT rar.id, weak.id, res.id
    FROM table1 rar, table2 weak, table2 res
    WHERE rar.rarity = `Common`
      AND weak.type = `Water`
      AND res.type = `Air`;

但是它不起作用,您可以帮助我吗?

I have the following tables:

Table1:

idrarity
1Common
2Uncommon
3Rare

Table2:

idType
1Air
2Earth
3Fire
4Water

The output table already exists and the schema is the following:

rarityIDweakness_typeIDresistance_typeID

and I should fill it with rows according to the Table2 and Table1.

For example if I'm given:

  • type is 'Water' and 'Air'
  • rarity is 'Common'

I'd like to add the IDs contained in Table1 and Table2 to this table to get the following updated output table:

rarityIDweakness_typeIDresistance_typeID
141

I've written the following query:

INSERT INTO table3 (rarityID, weakness_typeID, resistance_typeID)
    SELECT rar.id, weak.id, res.id
    FROM table1 rar, table2 weak, table2 res
    WHERE rar.rarity = `Common`
      AND weak.type = `Water`
      AND res.type = `Air`;

But it doesn't work, can you help me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

年华零落成诗 2025-02-05 07:29:35

我对您的问题的理解是,您正在尝试获取每个信息的ID。

如果这是正确的,为了执行此操作,您需要在以下查询中完成三个单独的查询中选择其ID:

INSERT INTO table3 (rarityID, weakness_typeID, resistance_typeID)
SELECT (SELECT rar.id
        FROM   table1 rar
        WHERE  rar.rarity = 'Common') AS rarityID,
       (SELECT weak.id
        FROM   table2 weak
        WHERE  weak.type = 'Water') AS weakness_typeID,
       (SELECT weak.id
        FROM   table2 weak
        WHERE  weak.type = 'Air') AS resistance_typeID;

如果要使用此代码播放,请检查此 sql小提琴

My understanding of your problem is that you're trying to get ids for each of your information.

If this is correct, in order to do this you need to select their ids in three separate queries like it is done in the following query:

INSERT INTO table3 (rarityID, weakness_typeID, resistance_typeID)
SELECT (SELECT rar.id
        FROM   table1 rar
        WHERE  rar.rarity = 'Common') AS rarityID,
       (SELECT weak.id
        FROM   table2 weak
        WHERE  weak.type = 'Water') AS weakness_typeID,
       (SELECT weak.id
        FROM   table2 weak
        WHERE  weak.type = 'Air') AS resistance_typeID;

If you want to play with this code, check this SQL Fiddle.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文