0

i have two tables

tb1

tb1_id          -       store_ids      -           date
  1             -        1,2,3,4       -        2023-01-01
  2             -            3,4       -        2023-06-01

tb2

tb2_id          -       name      -              date
 1              -       gold      -           2023-01-01
 2              -       mond      -           2023-01-01
 3              -       burgar    -           2023-01-01
 4              -       glass     -           2023-01-01
 5              -       blackD    -           2023-01-01

what i have tried is

sql
SELECT * 
FROM `tb2`
JOIN `tb1`
WHERE `tb2_id` IN (`store_ids`)

and i get error

'Warning: #1292 Truncated incorrect INTEGER value: 1,2,3,4'

8
  • You shouldn't store foreign keys as csv. That is very bad db design Commented Jan 25, 2023 at 6:50
  • read about find_in_set Commented Jan 25, 2023 at 6:51
  • find_in_set shows empty results @Jens Commented Jan 25, 2023 at 6:57
  • can you share your db strucure? because your query runs perfectly @diyeco5337 Commented Jan 25, 2023 at 7:05
  • @diyeco5337 mybe you use it in the wrong direction Commented Jan 25, 2023 at 7:06

2 Answers 2

2

You can use find_in_set

select * from tb1 join tb2 on find_in_set(tb2_id ,tbl1_id)

But as I mentioned in my earlier comment, it is better to redesign your table

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

You could try below query

SELECT * 
FROM `tb2`
JOIN `tb1`
WHERE `store_ids` REGEXP CONCAT('[[:<:]]',`tb2_id`,'[[:>:]]') -- MySQL 5.6
-- For MySQL 8.0, using WHERE `store_id` REGEXP CONCAT('\\b',`tb2_id`,'\\b')  

But it's better to not store foreign keys as list of ids separated by comma.

2 Comments

I think it would not work if you have id's > 10
@Jens You're correct. I've updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.