简体   繁体   中英

How do i select rows based on column of multiple related rows?

I am trying to select rows based on related (child) table column intersection with specific ids? Th idea is to select all packages that offer certain services in the related categories which the user selects.

I have a table of packages like this:

|  id  |   name    |
|------|-----------|
|  1   | Package 1 |
|  2   | Package 2 |
|  3   | Package 3 |

and a related child table like this:

|  id  |  service  | package-id | category-id |
|------|-----------|------------|-------------|
|  1   | service 1 |     1      |     A       |
|  2   | service 2 |     1      |     B       |
|  3   | service 3 |     2      |     C       |
|  4   | service 4 |     1      |     D       |
|  5   | service 5 |     3      |     C       |
|  6   | service 6 |     3      |     B       |
|  7   | service 7 |     3      |     A       |

Now lets say in my form i select categories [A,B] and want get all packages that contains services in category [A,B], how to do this correctly without having to write separate relational table?

The expected result should be rows 1 and 3.

Thanks for helping...

You can use GROUP_CONCAT like below. You would just need to do some formatting on input for the WHERE clause. I'm not overly familiar with MySQL, but I assume that's easy enough to do.

SELECT 
  P.*
FROM
(
  SELECT
    packageid,
    GROUP_CONCAT(Concat(',',categoryid,',') Order BY categoryid) categories
  FROM  Services
  Group BY packageid
)A
JOIN Packages P ON A.packageid = P.id
WHERE categories LIKE '%,A,%,B,%'

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