SQL FIDDLE: http://sqlfiddle.com/#!2/5895f/5
I have groups, each groups(item_group) can have many items(item) and each item has one status entry per user (item_status). I am trying to retrieve the last item for each group that was not from yourself. Think of it as a message thread, you only want to see as a preview of that thread the last message that was sent but that wasn't from you.
This works fine with my query
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;
However the next step is I want to make sure the status of any items of my items was not 0 this is where my problem is. It says Unknown column '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);