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

时间:2015-03-07 16:19:12

标签: sql sqlite

我有如下表格:

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

我想选择所有“逆变器”,以及附加到它们的“字符串”数量。

我在这里尝试了这个查询,但它给了我空的结果,所以我怎么能这样做?

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

我正在使用SQLite3。


这是我现在拥有的测试表的转储:

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');

3 个答案:

答案 0 :(得分:3)

似乎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;

这给出了:

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

答案 1 :(得分:0)

使用聚合始终意味着您正在进行分组,如果您没有指定分组,则它将是包含所有记录的单个组。对从inverter表中获取的字段进行分组。同样使用计数中的单个字段而不是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

答案 2 :(得分:-2)

更改表名"字符串"。这是一个保留字。