1

I've been trying to set up a small database with HeidiSQL but I've stumbled across a problem. I want to add in a column in a certain table that counts the amount of columns in another table containing a certain value. I've tried it by setting a default value, entering a custom value looking like this

    SELECT COUNT(LidID) AS AantalSchepen FROM SCHIP WHERE SCHIP.LidID=LID.LidID

Whereas LidID is the name of the column I want to count the number of rows, containing the same value in table SCHIP as in table LID. The value of LidID is the primary key of table LID, and therefor logically the foreign key in table SCHIP.

However, when I enter this statement in the custom default value field, it tells me the default value is invalid. Is what I'm doing completely impossible, or is my SQL statement flawed?

Edit: The purpose of the database is to be the source of info shown in a table on a website. As I've read in previous responses, what I'm trying to do here is simply impossible, so a different solution would be... ?

4

2 回答 2

0

In general, you cannot add a default value that "runs a query". This may depend on the database, but I can't think of a database that supports this.

What you can do is access the data using a view:

create view v_lid as
    select l.*,
           (select count(*)
            from SCHIP s
            where s.LidID = l.LidID
           ) as AantalSchepen
    from lid l;

Then, when you access the view, you will get the latest value for this.

Note: this is a bit different from a "default" value, which would put in the value when the row is created. If you really want that, you will need a trigger. Or, perhaps, there is some date logic that would arrive at the same value.

于 2015-04-24T12:46:44.660 回答
0

在 MySQL 5.7.6 和 MariaDB 5.2 以上,一个表可以有虚拟列。MariaDB 将其称为virtual,在 MySQL 中称为generated。两者含义相同,语法也非常相似。HeidiSQL 的表格编辑器支持创建这样的虚拟列。示例创建代码:

CREATE TABLE table1 (
 a INT NOT NULL,
 b VARCHAR(32),
 c INT AS (a mod 10) VIRTUAL
)

不幸的是,虚拟列不支持子查询,这就是为什么这一切都对COUNT(*)查询没有帮助。

于 2015-12-10T09:50:39.490 回答