I have a field named category_id
from my table contact
with as content, an id
or a list ids of categories
(1 or 1,2,3 ) per contact
.
Name of the categories coming from the category table who have id and name column.
I like to display the result of all categories name coming from the categories list from the contact table. How to do that ?
SELECT c.`id`,
(SELECT cat.`name`
FROM category cat
WHERE c.`category` in cat.`id` ) AS 'Categories'
FROM contact c
I tested this, but of course it's not working. The c. category
column content can be 1,2,3 or 3 .
Your have a category field which contains the literal text 1,2,3
? Then what you want is not directly possible. Fields are considered atomic entities in SQL, and your query is being parsed/executed as
WHERE c.category IN ('1,2,3')
aka
WHERE c.category = '1,2,3'
Instead of the
WHERE c.category IN ('1', '2', '3')
aka
WHERE (c.category = '1') OR (c.category = '2') OR (c.category = '3')
you're needing.
MySQL does have FIND_IN_SET()
for this sort of thing, but note that using it prevents use of indexes and your query performance will be crap on any largeish tables. It also renders your SQL non-portable.
SELECT con.`id`, cat.'name'
FROM contract con
INNER JOIN category cat ON con.'category' = cat.'id'
WHERE c.category IN ('1,2,3')
SELECT c.`id`, cat.'name'
FROM contract c
RIGHT JOIN category cat ON c.'category' = cat.'id'
WHERE c.category IN ('1,2,3')
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.