0

I have two tables. One is items. The second is items by categories (catitems). Both tables have a user field.

I need a query that selects all items by user in the first table (items) but excludes those items in the second table (catitem) assigned to a given category. In other words, I get a list of items by user from the first table but if there is a row in the 2nd table that has item, cat and user, I exclude the item.

Schematically this would be something like Select item FROM items where userid=1 but exclude item WHERE (in second table) (cat = "something" AND userid=1.)

I've tried the following but it's not excluding the item present in table 2. What am I doing wrong?

$sql = "SELECT i.*
FROM `items` i
LEFT JOIN `catitems` c
ON i.userid = c.userid
WHERE (c.userid = '$userid' && c.tcircle != '$cat')";
1
  • How do you match the items in the second table to those in the first? Can you show your table schema (the output of SHOW CREATE TABLE) for both tables? Commented Apr 30, 2012 at 15:36

2 Answers 2

1

First:

$sql = "SELECT i.*
FROM `items` i
LEFT JOIN `catitems` c
ON i.userid = c.userid
WHERE c.userid = '$userid'
AND c.tcircle != '$cat'";

Second: . Solution: .

Sign up to request clarification or add additional context in comments.

1 Comment

This also does not exclude the items for which a row is present in 2nd table.
0

A LEFT JOIN means all from left-side table (table listed first) vs a required match on the right-side. HOWEVER, once you apply the right-side table in a WHERE clause, it technically FORCES it to an inner join. As such, to fix your need, you need to move the "condition" associated with the other table to its corresponding ON clause...

SELECT i.*
   FROM items i
           LEFT JOIN catitems c
              ON i.userid = c.userid
             AND c.tcircle != '$cat'
   WHERE 
      i.userid = '$userid'

Small, but subtle difference. You ALWAYS want the "ITEM" associated for a user (via where i.userid instead of c.userid), but CONDITIONLLY, you only want the categories that are NOT '$cat' (found at the ON clause of the join)

2 Comments

To be clear, I do not want every item in left table for user...I want to exclude from those items, items found in right table. Above query still not excluding match in right table.
Joins did not seem well suited to task but following employing subquery works: $sql = "SELECT * FROM items WHERE userid = '$userid' AND id NOT IN (SELECT itemid FROM catitems WHERE userid='$userid' AND tcircle = '$cat')";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.