gpt4 book ai didi

mysql - 表 1 与表 2 外键引用的子项总和之间的 SQL 查询差异

转载 作者:行者123 更新时间:2023-11-29 06:58:24 25 4
gpt4 key购买 nike

假设我有 2 张 table :

表1

 ID    Name    Quantity
1 Pencil 12
2 Pen 35
3 Ruler 50

表2

 ID    Name    Quantity   FK_Table1
1 Pencil 6 1
2 Pencil 6 1
3 Pen 10 2
4 Pen 5 2
5 Pen 5 2
6 Pen 5 2
7 Ruler 12 3
8 Ruler 12 3
9 Ruler 12 3
10 Ruler 12 3
  • 我需要进行一个查询,仅从数量列中选择 table1 中的行,该行与 Table2 中具有相同 FK_Table1 值的所有数量列的总和不匹配

    (例如,铅笔不会被选择,因为它在table1中的数量为12,与table2中行ID#1和2的数量之和相同)。

  • 我需要进行一个查询,选择 table2 行而不是 table1 行,但应用相同的规则

我该怎么做?

最佳答案

尝试以下查询:

select * from table1 t1
where t1.Quantity <> (select sum(t2.Quantity) from table2 t2 where t2.FK_Table1 = t1.ID);

获取表2的记录:

select * from table2 where FK_Table1 IN(
select t1.ID from table1 t1
where t1.Quantity <> (
select sum(t2.Quantity) from table2 t2 where t2.FK_Table1 = t1.ID
)
);

关于mysql - 表 1 与表 2 外键引用的子项总和之间的 SQL 查询差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44693952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com