4

Okay no seriously, if a PostgreSQL guru can help out I'm just getting started.

Basically what I want is a simple table like such:

CREATE TABLE schema.searches
(
  search_id serial NOT NULL,
  search_query character varying(255),
  search_count integer DEFAULT 1,
  CONSTRAINT pkey_search_id PRIMARY KEY (search_id)
)
WITH (
  OIDS=FALSE
);

I need something like REPLACE INTO for MySQL. I don't know if I have to write my own procedure or something?

Basically:

  • check if the query already exists
  • if so, just add 1 to the count
  • it not, add it to the db

I can do this in my php code but I'd rather all that be done in postgres C engine

Kermit
  • 33,827
  • 13
  • 85
  • 121

1 Answers1

1

You have to add a unique constraint first.

ALTER TABLE schema.searches ADD UNIQUE (search_query);

The insert/replace command looks like this.

INSERT INTO schema.searches(search_query) VALUES ('a search query')
ON CONFLICT (search_query)
DO UPDATE SET search_count = schema.searches.search_count + 1;
Michas
  • 8,534
  • 6
  • 38
  • 62