在这个MySQL查询中苦苦挣扎。当我取出WHERE子句时,所有结果都会显示给用户。所以这不是php输出的问题。我很确定它是在WHERE子句中,但我已经被困住了很长时间而无法解决它。
$test = $db->query
("SELECT DISTINCT(a.id), a.name
FROM test AS a LEFT JOIN(testusers AS b,testclasses AS c, userclasses AS d)
ON (c.classID = d.classID AND a.id = b.testID)
WHERE d.userID='" . $_SESSION["id"] . "' OR b.userID= '" . $_SESSION["id"] . "'
GROUP BY a.id");
感谢您的帮助!
答案 0 :(得分:3)
您不应在WHERE子句中引用LEFT JOINed表(例如b.userID
)中的列。当你这样做时,你隐式将你的JOIN变成INNER JOIN。让这些测试成为JOIN条件的一部分。
不要这样做:
/* Wrong */
SELECT *
FROM test a
LEFT JOIN test2users b
ON a.id = b.testid
WHERE b.userID = 123
请改为:
/* Right */
SELECT *
FROM test a
LEFT JOIN test2users b
ON a.id = b.testid
AND b.userID = 123
答案 1 :(得分:1)
我清理了连接语句并删除了不必要的DISTINCT()。这给你带来了什么?
SELECT a.id, a.name
FROM " . $config["table_prefix"] . "test AS a
LEFT JOIN " . $config["table_prefix"] . "test2users AS b
ON a.id = b.testID
AND b.userID= '" . $_SESSION["id"] . "'
LEFT JOIN " . $config["table_prefix"] . "test2classes AS c
LEFT JOIN " . $config["table_prefix"] . "test2classes AS d
ON c.classID = d.classID
AND d.userID='" . $_SESSION["id"] . "'
GROUP BY a.id