简体   繁体   中英

How to filter resources with multiple characteristics with related tables in MYSQL

I have 3 tables in MYSQL.

[Resources]
Id
Name
....
[Characteristics]
Id
Name
...

"Resources" can have multiple "Characteristics" so i made the relation in other table:

[RecurCaract]
Id
IdRes (Id of Resource)
IdCha (Id of Characteristic)

So for example i have this records with this characteristics associated:

    Example 1 - Car1 / Car2 / Car3 / Car4
    Example 2 - Car1 / Car3
    Example 3 - Car2 / Car3
    Example 4 - Car3 / Car4

I need a query to show all the Resources with Car2 and Car3 selected (both).

In this example (Example 1 and Example 3)

To search the resources with characteristic numer 25 enabled... i can use this query:

SELECT Resources.Name, Characteristics.Name FROM Resources LEFT JOIN RecurCaract ON (Resources.Id=RecurCaract.IdRes) LEFT JOIN Characteristics ON (Characteristics.Id=RecurCaract.IdCha) WHERE Characteristics.Id = '25'

But... if i need the resources with characteristics numer 25, and number 3 enabled (both)... i have the problem.

SELECT Resources.Name, Characteristics.Name FROM Resources LEFT JOIN RecurCaract ON (Resources.Id=RecurCaract.IdRes) LEFT JOIN Characteristics ON (Characteristics.Id=RecurCaract.IdCha) WHERE Characteristics.Id = '25' AND Characteristics.Id = '3'

This query don't work.

What's is the best approach?

select r.name RESOURCE, c1.name Characteristic_1, c2.name Characteristic_2 from 
RecurCaract rc1 inner join RecurCaract rc2 on rc1.resource = rc2.resource left join 
resources r on r.id = rc1.resource left join characteristics c1 on c1.id = 
rc1.characteristic left join characteristics c2 on c2.id = rc2.characteristic
where rc1.characteristic = 25 and rc2.characteristic = 3;

This should work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM