I
I
ITicDigger2018-11-01 13:16:51
Database
ITicDigger, 2018-11-01 13:16:51

How to select with condition AND on the field of the connected 1-n table in SQL?

There are two tables: entity and entity properties.

Сущность:
Название | ID

Свойства:
ID сущности | свойство

How to select all entities with properties "1" and "2"?
Namely, so that both property 1 and property 2 are present in these entities.
The platform is Libre Office Base, but I'm just asking about SQL in the most general sense.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
ITicDigger, 2018-11-01
@ITicDigger

He himself invented such a bicycle (which later he made even shorter. See in the comment):

SELECT *
FROM "сущность"
WHERE
  (
    SELECT COUNT(*) FROM "свойства" WHERE "свойства"."ID сущности" = "сущность"."ID" AND
    (
      свойство = '1' OR
      свойство = '2'
    )
  ) = 2 --тут количество свойств на которые накладываются условия!

Seems not bad. If anyone knows better, please share.

G
getredtm1, 2018-11-01
@getredtm1

WITH cte AS (
SELECT * FROM Свойства 
WHERE свойство in (1,2)
)

SELECT Название 
FROM Сущность 
WHERE ID in (
SELECT distinct c.id 
FROM cte, Сущность c 
WHERE c.id = cte.id
GROUP BY (c.id)
HAVING COUNT(c.id) > 1
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question