[英]Returning rows with specific ID numbers with PHP and MYSQL?
I've been having difficulty returning the correct rows with my SQL query. 我一直很难用SQL查询返回正确的行。 I want to only return rows with either 31 or 34 as their album_items.id. 我只想返回31或34作为其album_items.id的行。 I want to exclude any other album_items.id from my results. 我想从结果中排除其他任何album_items.id。 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. 不管出于什么原因,即使是没有album_items.id为31或34的行仍会被返回。 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 谢谢你的时间,莎拉
I believe this is a problem with the order of operations. 我相信这是操作顺序的问题。
In you sql, you have 在你的SQL中,你有
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. 您需要在适当的地方加上括号。
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. 现在希望它将为您提供ID为31和34的行。
I think actually you are trying to do is: (joining item_table and album_table) 我想您实际上想做的是:(加入item_table和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')
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.