Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JOIN on array of ids in sql

I have three tables: TABLE 1 contracts

-------------------
id  |  contract_name
--------------------
1      test name
2      test name 2
2      test name 3
4      test name 4

TABLE 2 rooms

-------------------
id  |  room_name
--------------------
1      test name
2      test name 2
2      test name 3
4      test name 4

TABLE 3 promos

----------------------------------
 id  |  contracts_id  |   rooms_id
----------------------------------
 1          1,3            1,3,4
 1          2              1,2,3

No I am trying to do an inner join to get the names of the contract and the rooms according to the ids in the array saved in database. I know this is not ideal at all, but I can not change the database set up. So here is what I would like to do with my query, but obviously it is impossible. Does anyone have any idea on how I can accomplish this?

mysql_query("SELECT pb.*, c.contract_name, r.room_name FROM promo_blackouts AS pb
INNER JOIN contracts as c ON c.contract_id IS IN pb.contracts_id
INNER JOIN rooms as r ON r.room_id IS IN pb.rooms_id 
WHERE pb.promo_id = '$promo_id'") or die(mysql_error());
like image 911
luv2code Avatar asked Sep 12 '25 10:09

luv2code


1 Answers

Are you looking for something like this?:

SELECT DISTINCT
    contract_name,
    room_name
FROM
    promos
INNER JOIN
    contracts ON FIND_IN_SET(contracts.id, contract_id) != 0
INNER JOIN
    rooms ON FIND_IN_SET(rooms.id, room_id) != 0
WHERE
    promos.id = 1
like image 81
MichaelRushton Avatar answered Sep 15 '25 00:09

MichaelRushton