B
B
B1ackGh0st2018-04-25 11:09:41
PostgreSQL
B1ackGh0st, 2018-04-25 11:09:41

How to organize a search in 5 PostgreSQL database tables?

Hey!
There are 5 tables

CREATE TABLE subscriber
(
  id integer NOT NULL DEFAULT nextval('subscriber_id_seq'::regclass),
  object_id integer,
  subdivision_id integer,
  name character(255),
  "position" integer
)

CREATE TABLE subdivision
(
  id integer NOT NULL DEFAULT nextval('subdivision_id_seq'::regclass),
  object_id integer,
  name character(255),
  "position" integer
)

CREATE TABLE phone
(
  id integer NOT NULL DEFAULT nextval('phone_id_seq'::regclass),
  subscriber_id integer,
  phone character(64)
)

CREATE TABLE object
(
  id integer NOT NULL DEFAULT nextval('object_id_seq'::regclass),
  name text,
  "position" integer
)

CREATE TABLE email
(
  id integer NOT NULL DEFAULT nextval('email_id_seq'::regclass),
  subscriber_id integer,
  email character(255)
)

How to search all tables in fields:
subscriber -> name
email -> email
phone -> phone
subdivision -> name
object -> object
subscriber -> name
Tried like this:
$sqlSearch = "SELECT
        subscriber.name,
        object.name,
        subdivision.name,
        phone.phone,
        email.email
        FROM subscriber
        LEFT JOIN phone ON (phone.subscriber_id = subscriber.id)
        LEFT JOIN email ON (email.subscriber_id = subscriber.id)
        LEFT JOIN object ON (object.id = subscriber.object_id)
        LEFT JOIN subdivision ON (subdivision.id = subscriber.subdivision_id)
        WHERE
        subscriber.name ~*'.$search.' OR
        phone.phone ~*'.$search.' OR
        email.email ~*'.$search.' OR
        object.name ~*'.$search.' OR
        subdivision.name ~*'.$search.'";

but this query does not look into object.name and subdivision.name

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alexalexes, 2018-04-25
@alexalexes

Pay attention to the shape of the quotation marks.
If " " is used, then you can insert variables inside directly "text $search some text".
If ' ', then the variable can only be pasted 'text ' . $search. ' some text'.
If the text is the text of the request, then the developer should be scolded and beaten for inserting or pasting parameters directly.
PS: I'm tired of reminding you, never glue query parameters with query text directly - this is the door to sql injection!
php.net/manual/ru/function.pg-query-params.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question