Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

mysql - How to fill a SQL column with data (calculated) from another table

I have a question and don't know how to approach the problem exactly.

I have two tables as following:

Clients
| c_id | name    | reference |
| ---- | ------- | --------- |
| 1    | ClientA | 1         |
| 2    | ClientB | 1         |
| 3    | ClientC | 2         |
| 4    | ClientD | 2         |
| 5    | ClientE | 1         |
| 1    | ClientF | 3         |

Tour
| t_id | name    | count |
| ---- | ------- | ----- |
| 1    | TourA   | 3     |
| 2    | TourB   | 2     |
| 3    | TourC   | 1     |

"Reference" in the "Client" table is defined as foreign key.

Is it possible to fill the column "count" in the table "Tour" with an automated formula where it counts how many times the t_id appears in the "Client" table?

Something like: COUNT(c_id) FROM clients WHERE reference = t_id

I have read about to create a view but not sure how to fetch the data correctly.

Thanks for your help, Raphael

UPDATE #1:

The workflow as described with the view works perfectly. I'm trying now to fill the column via a trigger but I'm getting an SQL error with the following code:

CREATE TRIGGER client_count 
AFTER UPDATE
ON clients FOR EACH ROW

SELECT t.*, 
    (
        SELECT COUNT(*) FROM clients c where c.tour_id = t.tour_id
    ) AS tours.tour_bookedspace
FROM tours t

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The view you have referred to is indeed the way to go here. The view you need to create needs to join the two tables and perform a count aggregation as follows:

CREATE VIEW vwTour
AS
SELECT  t.t_id,
        t.name,
        COUNT(t.name) AS Cnt
FROM    tour t
        JOIN Clients c
            ON t.t_id = c.reference
GROUP BY t_id,
        t.name

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...