如何在mysql中引用另一个表的字段?

如何在mysql中引用另一个表的字段?,mysql,Mysql,有两个表,我想实现如下内容 images[id].referenced = count(articles[image_id = id]) >= 1 articles: images: ,---------------------------------. ,--------------------------------. | id | INT | PRIMARY | | id | INT

有两个表,我想实现如下内容

images[id].referenced = count(articles[image_id = id]) >= 1

articles:                            images:
,---------------------------------.  ,--------------------------------.
| id          | INT     | PRIMARY |  | id         | INT     | PRIMARY |
|-------------|---------|---------|  |--------------------------------|
| image_id    | INT     |         |  | url        | VARCHAR |         |
|-------------|---------|---------|  |------------|-------------------|
| name        | VARCHAR |         |  | referenced | BOOLEAN |         |
`---------------------------------'  `--------------------------------'
i、 e.images[id]。仅当存在图像id=id的任何文章时,引用才为真

我应该如何做到这一点

使现代化 对不起,把问题弄糊涂了。我希望在更新某些相关的article.image\u id时,每行的images.referenced自动更新

例如:

初始数据:

articles:
| id | image_id | name                   |
|----|----------|------------------------|
| 1  | 2        | First Article          |
| 2  | 3        | The author is an idiot |

images:
| id | url                         | referenced |
|----|-----------------------------|------------|
| 1  | http://example.com/images/1 | false      |
| 2  | http://example.com/images/2 | true       |
| 3  | http://example.com/images/3 | true       |

当执行类似sql的更新文章集image_id=1,其中id=2时,我希望表映像也会自动更新,因为id=1的引用值等于true,id=3的引用值等于false,因为文章引用了映像[3],即文章[2]现在引用了映像[1]。

如果要更新该值,可以执行以下操作:

update images i
    set referenced = (select count(*) from articles a where a.image_id = i.id) > 0;
更有效的方法是:

update images i
    set referenced = exists (select 1 from articles a where a.image_id = i.id) > 0;

这将设置值一次。如果需要维护该值,则需要插入/更新/删除触发器。我不推荐这种方法。我建议只使用select查询语句,根据需要从两个表中获取结果。

示例数据和预期结果将非常有用。。。你只是想加入吗?