我对一个比较复杂的查询有点麻烦,我不知道到底出了什么问题。。。
查询处理两个MySQL表:

$userstable:
|| id || firstname || lastname
|| 1  || John      || Doe

$membershipstable:
|| groupid || templateid || userid ||
||   0     ||     1      ||    1   ||
||   1     ||     0      ||    2   ||
||   0     ||     2      ||    3   ||

以下是查询:
$query = "
    SELECT DISTINCT
        u.id,
        u.firstname,
        u.lastname
    FROM $userstable AS u
    INNER JOIN $membershipstable AS M1 ON u.id = M1.userid
    INNER JOIN $membershipstable AS M2 ON M1.groupid = M2.groupid
    WHERE M2.templateid = :currenttemplateid
    ";

作为参考,我已经对占位符:currenttemplateid的变量进行了双重检查,它返回的结果正确。。。我要做的是只从查询记录中返回当前模板的id,但是查询从$userstable返回与模板关联的任何用户的用户数据,而不管该模板的id是否与WHERE子句中指定的当前模板匹配。
如果我刚刚完全了解了这一点,那么我很抱歉,但我已经用这个代码工作了几个小时,所以我的感觉可能没有他们应该的那么敏锐。。。非常感谢您的帮助。

最佳答案

按如下方式修改查询:-

$query = " SELECT DISTINCT u.id, u.firstname, u.lastname
           FROM $userstable AS u
           INNER JOIN $membershipstable AS M1 ON u.id = M1.userid
           INNER JOIN $membershipstable AS M2 ON M1.groupid = M2.groupid and M2.templateid = :currenttemplateid ";

10-08 09:28
查看更多