如何在一个表中查询结果,然后继续查找包含这些结果的其他相关信息

时间:2013-12-12 17:56:08

标签: mysql sql

我的user_type_of_therapy表包含2列member_numtype_of_therapy。每个成员都要重复,因为他们可以有多个type_of_therapy

我需要获取X成员信息。如果有的话,请使用type_of_therapy(是一个ID)并搜索type_of_therapy表。得到该治疗类型的名称。

我知道如何进行独立查询以获取该信息。但我不确定我能否在一次查询中做到这一切?我找到了一些例子,但我尝试的任何东西似乎都没有用。

这不是内连接....我需要第二个表中的结果,这是第一个表获取结果的直接链接。

2 个答案:

答案 0 :(得分:-1)

你试过JOIN吗?

SELECT user_type_of_therapy.member_num, type_of_therapy.type_of_therapy FROM user_type_of_therapy JOIN type_of_therapy ON type_of_therapy.type_of_therapy = user_type_of_therapy.type_of_therapy

答案 1 :(得分:-1)

是的,您可以使用联接(http://dev.mysql.com/doc/refman/5.0/en/join.html)。 要获得用户数据和治疗名称,您可以这样做(我使用任意表名,因为我不知道您的确切表结构):

SELECT
    user.*, type_of_therapy.name
FROM users
    INNER JOIN user_type_of_therapy ON
        users.member_num = user_type_of_therapy.member_num
    INNER JOIN type_of_therapy ON
        user_type_of_therapy.type_of_therapy = type_of_therapy.type_of_therapy
WHERE
    users.[whatever filter you want to use for the users]

或者如果您不希望将所有类型作为单独的行获取,请在查询末尾添加GROUP BY users.member_num并执行

SELECT user.*, GROUP_CONCAT(type_of_therapy.name SEPARATOR ',') as types_of_therapy

通过这种方式,您可以在一栏中获得所有类型的治疗。