SQL FIDDLE:http ://sqlfiddle.com/#!2/5895f/5
我有组,每个组(item_group)可以有很多项目(item),每个项目每个用户都有一个状态条目(item_status)。我正在尝试检索不是您自己的每个组的最后一项。将其视为消息线程,您只想查看该线程的预览,即最后发送但不是来自您的消息。
这适用于我的查询
SELECT * FROM (
SELECT it.id as group_id, i.sender_id as sender_id
FROM item_group it
JOIN item i ON (i.item_group_id = it.id)
JOIN item_status s ON (s.item_id = i.id)
) as results
WHERE results.sender_id != 2
GROUP BY results.group_id;
但是下一步是我想确保我的项目的任何项目的状态不是 0 这是我的问题所在。它说未知列'results.group_id'
SELECT * FROM (
SELECT it.id as group_id, i.sender_id as sender_id
FROM item_group it
JOIN item i ON (i.item_group_id = it.id)
JOIN item_status s ON (s.item_id = i.id)
) as results
WHERE results.sender_id != 2
AND (SELECT COUNT(*) = 0
FROM item_status s
--- PROBLEM IS HERE results.group_id ---
JOIN item i ON (i.item_group_id = results.group_id AND s.item_id = i.id)
----------------------------------------
WHERE s.user_id = 2 AND s.status = 0)
GROUP BY results.group_id;
CREATE TABLE item_group (
id int(10) PRIMARY KEY NOT NULL AUTO_INCREMENT);
CREATE TABLE item (
id int(10) PRIMARY KEY NOT NULL AUTO_INCREMENT,
item_group_id int(10) NOT NULL,
sender_id MEDIUMINT UNSIGNED NOT NULL);
CREATE TABLE item_status (
item_id int(10) NOT NULL,
user_id MEDIUMINT UNSIGNED NOT NULL,
status int(10) NOT NULL);
INSERT INTO item_group (ID) VALUES (1);
INSERT INTO item (item_group_id, sender_id) VALUES (1, 1);
INSERT INTO item (item_group_id, sender_id) VALUES (1, 2);
INSERT INTO item_status (item_id, user_id, status) VALUES (1, 1, 1);
INSERT INTO item_status (item_id, user_id, status) VALUES (1, 2, 1);
INSERT INTO item_status (item_id, user_id, status) VALUES (2, 1, 1);
INSERT INTO item_status (item_id, user_id, status) VALUES (2, 2, 1);