Reputation: 222
I've been having difficulty returning the correct rows with my SQL query. I want to only return rows with either 31 or 34 as their album_items.id. I want to exclude any other album_items.id from my results. The main line I'm focused on is:
WHERE album_items.album IN (31,34)
For whatever reason, even the rows that don't have album_items.id of 31 or 34 are still being returned. Here's the full query. Is it possible that I haven't used to right syntax?
SELECT * FROM items_table
RIGHT JOIN items_table
ON items_table.id=album_items.id
WHERE album_items.album IN (31,34)
AND items_table.name LIKE '%{$term}%'
OR items_table.description LIKE '%{$term}%'
AND items_table.active != '0'
Thanks for your time, Sarah
Upvotes: 0
Views: 65
Reputation: 1729
SELECT * FROM items_table
RIGHT JOIN album_items
ON items_table.id=album_items.id
WHERE album_items.album IN (31,34)
AND (items_table.name LIKE '%{$term}%'
OR items_table.description LIKE '%{$term}%'
AND items_table.active != '0')
Use () to make the order correct. Now hopefully it will give you rows with id 31 and 34 only.
I think actually you are trying to do is: (joining item_table and album_table)
SELECT * FROM items_table
RIGHT JOIN album_items
ON items_table.id=album_items.id
WHERE album_items.album IN (31,34)
AND (items_table.name LIKE '%{$term}%'
OR items_table.description LIKE '%{$term}%'
AND items_table.active != '0')
Upvotes: 0
Reputation: 92785
I guess your query should look like this
SELECT *
FROM items_table i RIGHT JOIN album_items a
ON i.id = a.id
WHERE a.album IN (31, 34)
AND (i.name LIKE '%{$term}%' OR i.description LIKE '%{$term}%')
AND i.active != '0'
Upvotes: 0
Reputation: 106
I believe this is a problem with the order of operations.
In you sql, you have
WHERE album_items.album IN (31,34)
AND items_table.name LIKE '%{$term}%'
OR items_table.description LIKE '%{$term}%'
AND items_table.active != '0'
Which is interpreted as
WHERE
(album_items.album IN (31,34) AND items_table.name LIKE '%{$term}%')
OR
(items_table.description LIKE '%{$term}%' AND items_table.active != '0')
Most likely, the second condition is causing the extra rows. You'll want to include parenthesis where appropriate.
Upvotes: 1