简体   繁体   English

如何在mysql中对生成的列使用select语句?

[英]How to use a select statement for a generated column in mysql?

I have 2 tables.我有2张桌子。

table_1:
Id.    Name        Surname.   company_id
1      tony.       tata.      fiat
2      Michael.    folks.     fiat
3      Salvo       ture.      alfa 

table_2:
company_id.   street.          cap.        numbers_of_guys
fiat          via le maini.    20123.      2
alfa          stazione x.      20123.      1
foo           novara           20145.      0 

I would like to create a generated column that counts how many rows I have in table_1.company_id = table_2.company_id and stores it in table_2.numbers_of_guys我想创建一个生成的列来计算我在 table_1.company_id = table_2.company_id 中有多少行并将其存储在 table_2.numbers_of_guys 中

How can i insert a query statment as default expression?如何插入查询语句作为默认表达式?

SELECT COUNT(table_1.id)
FROM table_2
INNER JOIN table_1 USING (company_id)

You shouldn't store easily calculated columns you could extend you query to include a group by.您不应该存储容易计算的列,您可以扩展查询以包含分组依据。

SELECT t2.`company_id.`, t2.`street.`, t2.`cap.` , COUNT(table_1.id)
FROM table_2 t2
LEFT JOIN table_1 t1 on t1.company_id = t2.`company_id.`
group by t2.`company_id.`, t2.`street.`, t2.`cap.` 

BTW do your table column names really terminate with a full stop if so you will always need to enclose them in backticks.顺便说一句,如果您总是需要将它们括在反引号中,您的表列名是否真的以句号结尾。 Also although using is syntactically correct it's better (in my view) to explicitly state both sides of the join, Also note the LEFT join.此外,尽管 using 在语法上是正确的,但(在我看来)最好明确说明连接的双方,还要注意 LEFT 连接。

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

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