字段中的mysql数组与其他表连接

时间:2012-07-06 07:38:58

标签: mysql join field

我有两张桌子:reasonuser

reason (id, reason)
user (id, name, reason_id)
数据中的

reason (1, 'ok'), (2, 'no problem')
user (1, 'eko', '1,2')

我需要这样的观点:

    id | name | reason
    1  | eko  | ok, no problem

是否可能这样做?

2 个答案:

答案 0 :(得分:0)

select u.id,u.name,r.reason 
from user u left join reason r 
on u.reason_id = r.id;

答案 1 :(得分:0)

试试这个解决方案:

SELECT
    a.id, 
    a.name,
    GROUP_CONCAT(b.reason ORDER BY b.id SEPARATOR ', ') AS reason
FROM
    user a
INNER JOIN
    reason b ON SUBSTRING(a.reason, FIND_IN_SET(b.id, a.reason) + (FIND_IN_SET(b.id, a.reason) - 1), 1) = b.id
GROUP BY
    a.id

作为旁注,你所拥有的是一个糟糕的数据库设计。 usersreasons之间的关系是N:M(多对多)关系。 一个用户可能有很多原因;许多用户可能会有一个原因 ......

建立此关系的最佳方法是使用交叉引用表来存储useridreasonid的唯一组合:

+-------------+   +-------------------+   +---------------+
| users       |   | users_has_reasons |   | reasons       |
+-------------+   +-------------------+   +---------------+
| userid [PK] |   | userid [PK]       |   | reasonid [PK] |
| name        |   | reasonid [PK]     |   | reason        |
| etc...      |   +-------------------+   | etc...        |
+-------------+                           +---------------+

然后得到相同的结果,你可以这样做:

SELECT
    a.userid, 
    a.name,
    GROUP_CONCAT(c.reason ORDER BY c.reasonid SEPARATOR ', ') AS reason
FROM
    users a
INNER JOIN
    users_has_reasons b ON a.userid = b.userid
INNER JOIN 
    reasons c ON b.reasonid = c.reasonid
GROUP BY
    a.userid

MUCH 效率更高,因为您的联接将通过索引发生,并且 MUCH 更易于管理(即插入,更新,删除等)。< / p>