Reputation: 57
I am using PostgreSQL 9.1 on Windows.
I am collecting data automatically from a machine into a PostgreSQL DB and this is working correctly. The data is being saved in several tables and the one I am interested in is called testrecord
. I have a second static table called testcode
and a join between the tables. I want to select some of the incoming data in testrecord
and populate a new table called finaldata
, where there is a match on parameter
and the testid
which is not blank (null).
Question 1
Is an INSERT INTO
and JOIN
the best way of doing this?
Question 2
All the fields at the moment are varchar. When I add a integer field
in the table finaldata
(such as auto incrementing serial) I get
messages such as column "FdataID" is of type integer but expression
is of type character varying
or column "FdataID" is of type integer
but expression is of type record
The code for my function is below:
INSERT INTO finaldata
SELECT
"testrecord"."Record",
"testrecord"."Sample",
"testrecord"."SampleOrig",
"testrecord"."Parameter",
"testrecord"."Result",
"testrecord"."ResultOrig",
"testrecord"."Units",
"testrecord"."OperatorID",
"testrecord"."ObsTime",
"testrecord"."MsgTime",
"testcode"."Machine",
"testcode"."TestName",
"testcode"."ShortTestName",
"testcode"."TestID"
FROM testrecord
LEFT OUTER JOIN testcode
ON ("testrecord"."Parameter" = "testcode"."Parameter")
AND ("testrecord"."Machine" = "testcode"."Machine")
WHERE ("testcode"."TestID") IS NOT NULL;
Upvotes: 0
Views: 3121
Reputation: 66243
You wrote:
INSERT INTO finaldata
SELECT "testrecord"."Record", /* some column skipped */
FROM testrecord LEFT OUTER JOIN testcode ON ("testrecord"."Parameter" = "testcode"."Parameter") AND ("testrecord"."Machine" = "testcode"."Machine")
WHERE ("testcode"."TestID") IS NOT NULL;
The first thing is: Into which columns shall INSERT
write the stuff produced by the SELECT
part? You have to specify it like this:
INSERT INTO finaldata ("Record", ...)
SELECT "testrecord"."Record", /* some column skipped */
...
Your strange message about wrong types might be caused by this.
The second thing is:
... WHERE ("testcode"."TestID") IS NOT NULL;
Any you imply that you want to use this code inside a function (the trigger function I guess). Each call to this statement would not just insert one new row into finaldata
, it would insert everything. Duplicate entries are then a certain thing.
So:
INSERT
partSELECT
part.Oh, yes, question one: As long as a SELECT
query produces the correct data, it is good enough to be used within an INSERT
:-) If a JOIN
helps to produce the correct data -- that's OK.
Upvotes: 1