Yanipan
Yanipan

Reputation: 664

unclear mySql query syntax

A client requested me to perform some changes in an SQL query and sent me exactly the query he wanted. He usually works on msSql but says it should work also on MySql which is the platform i'm using.

This is the query :

INSERT INTO     Messages (Match, Message)
SELECT          [Match], MM.Message
FROM            MatchMessages AS MM
INNER JOIN  Matches AS M
ON      MM.ActionBy=M.ActionBy
AND     MM.Status=M.Status

I'm not sure where the insert get the correct values from the select and join, and how does it know where to enter which value. What is happening in this query? There is no VALUES anywhere and there are more selected values then targeted in the insert...

Does this query looks logical?

Upvotes: 0

Views: 46

Answers (1)

Yahia
Yahia

Reputation: 70369

Yes - it is an absolutely normal query... Let's break this down:

Part one

SELECT          [Match], MM.Message
FROM            MatchMessages AS MM
INNER JOIN  Matches AS M
ON      MM.ActionBy=M.ActionBy
AND     MM.Status=M.Status

This gets executed first and returns 0-n rows of data... each row containing 2 columns (Match and Message) in this specific order. If you want just execute it standalone (exactly as it is here without the INSERT part).

Part two

INSERT INTO     Messages (Match, Message)

This part gets fed the result of Part one (beware that this part does not know and does not care about the column names from Part one, it just acts on the order of columns)... which means for every row returned by Part one it does the equivalent of

INSERT INTO Messages (Match, Message) VALUES (MatchFromPartOne, MessageFromPartOne)

Upvotes: 4

Related Questions