0

A mysql query is vexing me. I have some javascript that lets users assign people to a category by moving them back and forth between two buckets (boxes). The first bucket should be all people except those in second bucket (assigned to category). The second bucket consists of people in a category. Therefore, I need a mysql query for the first bucket that pulls all the people except those pulled in the second query (assigned to category).

I have one table of all people and a second of people assigned to categories. (There is also a third table of categories ignored here.) The following code returns the selected group for the second bucket (those in the category) but for the first bucket only pulls those already assigned to some category when I want it to include people who do not even appear in the catpeople table.

I think problem has something to do with NULL or my join but cannot figure it out. Would appreciate any suggestions:

people

id | name

catpeople

id | catid | peopleid

First query should pull all people except those in second query but it only pulls people who show up in catpeople table.

$sql1 = "SELECT * FROM `people` c
LEFT JOIN `catpeople` c 
on p.id = c.peopleid
WHERE catid <> '2'";

Second query works works fine (pulls people in category)

$sql2 = "SELECT * FROM `people` p
LEFT JOIN `catpeople` c 
on p.id = c.peopleid
WHERE catid = '2'";
4

2 回答 2

2

拥有让你的catpeople.catid='2'内在。如果您需要所有人将条件移动到:WHEREJOINON

$sql1 = "SELECT * FROM `people` p
LEFT JOIN `catpeople` c 
ON (p.id = c.peopleid AND catid <> '2')";

如果我正确理解了您的问题,则需要稍微修改此查询:

$sql1 = "SELECT p.* FROM `people` p
LEFT JOIN `catpeople` c 
ON (p.id = c.peopleid AND catid <> '2')"
WHERE c.id IS NULL ; -- I guess c.id is a primary key in catpeople.
--now it returns rows in people table that have no rows 
--associated with them in catpeople (or rows with catid =2 or catid is null)
于 2012-10-06T12:06:24.427 回答
0

LEFT JOIN 无论如何都会拉人。使用 INNER JOIN 代替:

$sql1 = "SELECT * FROM `people` c
INNER JOIN `catpeople` c 
on p.id = c.peopleid AND catid <> 2;
于 2012-10-06T12:08:20.720 回答