我有两个表:请求和位置
请求的示例数据
request id | requestor | locations
1 | ankur | 2,5
2 | akshay | 1
3 | avneet | 3,4
4 | priya | 4
地点的示例数据
loc_id | loc_name |
1 | gondor
2 | rohan
3 | mordor
4 | bree
5 | shire
我想找到特定位置的request_id。如果我使用location_id执行此操作,我会得到正确的结果。
select request_id from request where locations like "%,3%" or locations like "%3,%";
此查询为我提供了针对位置id = 3
的请求如何为loc_name实现此目的?用
替换查询的“like”部分中的数字select loc_id from locations where loc_name = "mordor"
任何有关这方面的帮助都会非常有帮助。感谢。
答案 0 :(得分:3)
您可以使用FIND_IN_SET()
SELECT *
FROM request r JOIN locations l
ON FIND_IN_SET(loc_id, locations) > 0
WHERE loc_name = 'mordor'
这是 SQLFiddle 演示
但是,通过引入可能看起来像
的多对多表,您可以更好地规范化您的数据CREATE TABLE request_location
(
request_id INT NOT NULL,
loc_id INT NOT NULL,
PRIMARY KEY (request_id, loc_id),
FOREIGN KEY (request_id) REFERENCES request (request_id),
FOREIGN KEY (loc_id) REFERENCES locations (loc_id)
);
从长远来看,这将节省大量时间,使您能够正常维护和查询数据。
您的查询可能看起来像
SELECT *
FROM request_location rl JOIN request r
ON rl.request_id = r.request_id JOIN locations l
ON rl.loc_id = l.loc_id
WHERE l.loc_name = 'mordor'
甚至
SELECT rl.request_id
FROM request_location rl JOIN locations l
ON rl.loc_id = l.loc_id
WHERE l.loc_name = 'mordor';
如果您只需要返回request_id
这是 SQLFiddle 演示
答案 1 :(得分:1)
解决方案,如果locations是varchar字段!
使用类似的字符串连接表格(将r.locations连接到起始和结束逗号)
代码未经测试:
SELECT
r.request_id
FROM location l
INNER JOIN request r
ON CONCAT(',', r.locations, ',') LIKE CONCAT('%,',l.loc_id,',%')
WHERE l.loc_name = 'mordor'
答案 2 :(得分:0)
试试这个
SELECT *
FROM request
CROSS JOIN
(
SELECT 1 AS loc
UNION ALL
SELECT 2 AS loc
UNION ALL
SELECT 3 AS loc
UNION ALL
SELECT 4 AS loc
UNION ALL
SELECT 5 AS loc
) q
JOIN Location
ON loc_id = CAST(NULLIF(SUBSTRING_INDEX(locations, ',', -loc), SUBSTRING_INDEX(locations, ',', 1 - loc)) AS UNSIGNED)