简体   繁体   English

计算另一个表中通过外键引用当前行的行

[英]Count rows from another table referencing current row by foreign key

I have tables as follows: 我有如下表格:

inverter [ id, address, ... ]
string [ id, inverter_id (foreign key), ... ]

I want to select all "inverters", together with the number of "strings" attached to them. 我想选择所有“逆变器”,以及附加到它们的“字符串”的数量。

I tried this query here, but it gives me empty result, so how can I do this? 我在这里尝试了此查询,但是它给了我空的结果,那么我该怎么做呢?

SELECT inverter.*, COUNT(string.*) as string_count
FROM inverter 
LEFT JOIN string ON string.inverter_id = inverter.id
ORDER BY address

I am using SQLite3. 我正在使用SQLite3。


Here's a dump of the test tables I have now: 这是我现在拥有的测试表的转储:

CREATE TABLE `inverter` (`id` INTEGER NULL PRIMARY KEY AUTOINCREMENT, `address` VARCHAR(3) NULL, `comment` VARCHAR(250) NULL);

INSERT INTO "inverter" ("id","address","comment") VALUES ('2','A1','North side');
INSERT INTO "inverter" ("id","address","comment") VALUES ('3','A2','Broken inverter');
INSERT INTO "inverter" ("id","address","comment") VALUES ('4','A3','');
INSERT INTO "inverter" ("id","address","comment") VALUES ('5','A4','South-west corner');


CREATE TABLE `string` (`id` INTEGER NULL PRIMARY KEY AUTOINCREMENT, `address` VARCHAR(3) NULL, `inverter_id` INTEGER NULL, `comment` VARCHAR(250) NULL, FOREIGN KEY (`inverter_id`) REFERENCES `inverters` (`id`) ON DELETE SET NULL);

INSERT INTO "string" ("id","address","inverter_id","comment") VALUES ('1','XX','3','');
INSERT INTO "string" ("id","address","inverter_id","comment") VALUES ('2','XY','3','Ahoj jak se máš');
INSERT INTO "string" ("id","address","inverter_id","comment") VALUES ('3','XZ','4','Moo');

It seems SQLite3 chokes on count(s.*) so try this instead: 似乎SQLite3在count(s.*)上令人窒息,因此请尝试以下操作:

select i.*, count(s.id) 
from inverter i 
left join string s on i.id = s.inverter_id group by i.address;

This gives: 这给出:

2|A1|North side|0
3|A2|Broken inverter|2
4|A3||1
5|A4|South-west corner|0

Using an aggregate always means that you are grouping, and if you don't specify the grouping it will be a single group containing all records. 使用聚合始终意味着您正在分组,如果不指定分组,它将是包含所有记录的单个组。 Group on the fields that you get from the inverter table. 对从inverter表中获得的字段进行分组。 Also use a single field in the count instead of string.* : 还可以在count中使用单个字段,而不是string.*

select
  inverter.id, inverter.address, count(string.id) as string_count
from
  inverter 
  left join string on string.inverter_id = inverter.id
group by
  inverter.id, inverter.address
order by
  inverter.address

Change the table name "string". 更改表名称“字符串”。 That is a reserved word. 那是保留字。

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

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