Skip to content
Advertisement

How can I filter one column by two AND conditions?

The question has been resolved. But if you have a “better” or another way to do it then feel free to add a comment! Thanks all for reading! 🙂

I’m trying to make a dynamic query. Everything is working perfectly except for one thing. I’ve Google’d for days but I can’t figure out how I can make the following work;

JavaScript

The query executes but does not return anything. The problem is that the SDG.id can’t be true to both :SDG_1 and :SDG_2.

Using the OR operator works, but that does not return it the way I want. It must “act” as an AND operator. (:SDG_1 & :SDG_2 are the names of the PHP variables that bind to the SQL statement parameters.)

The query should filter for both values. The values given to :SDG_1 and :SDG_2 must both exist in the SDG.id column of the project_SDG table. If the value of :SDG_1 exists, but :SDG_2 not, then the query should not return anything.

I found this on StackOverflow but it did not work for me: SELECTING with multiple WHERE conditions on same column

I hope someone can help me out.

EDIT: minimal reproducible example

QUERY:

JavaScript

Project table

JavaScript

SDG table

JavaScript

project.SDG (bridge-table)

JavaScript

Advertisement

Answer

You want for each project.id both values :SDG_1 and :SDG_2 to exist for SDG.id, so use this in the WHERE clause:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement