D
D
danys_kun2021-08-14 20:16:09
MySQL
danys_kun, 2021-08-14 20:16:09

How to compare two fields VARCHAR and INT?

Maybe I'm asking a very stupid question, but how can I correctly compare two fields in different tables?
There is a first table with news, each news has a field with type VARCHAR and value for example 1,13,14, and there is a second table with categories (name, ID, etc.).
The question is, how do I compare the ID from the second table with the VARCHAR field from the first?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alexalexes, 2021-08-14
@danys_kun

What your problem looks like:
News table:
ID, CATEGORIES
1, '1,13,14'
How to implement:
Add another table Categories_Of_News
ID, NEWS_ID, CATEGORY_ID
1, 1, 1
2, 1, 13
3, 1, 14
Then queries will not contain any crutches with string parsing and indexes will work for you (if you create them).
For example, get all categories that include news :news_id

select  C.Id
from News N
join Categories_Of_News CoN on CoN.News_Id = N.Id
join Category C on C.Id = CoN.Category_Id 
where N.Id = :news_id

PS: See how to implement a many-to-many relationship.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question