SELECT SQL_CALC_FOUND_ROWS o . * , titles.title AS title, categories.category AS category,
images.image AS image, urls.url AS url, descriptions.description AS description,
from_sites.from_site AS from_site, prices.price AS price
FROM oglasi AS o
LEFT JOIN titles ON o.title_id = titles.title_id
LEFT JOIN categories ON o.category_id = categories.category_id
LEFT JOIN images ON o.image_id = images.image_id
LEFT JOIN urls ON o.url_id = urls.url_id
LEFT JOIN descriptions ON o.description_id = descriptions.description_id
LEFT JOIN from_sites ON o.from_site_id = from_sites.from_site_id
LEFT JOIN prices ON o.price_id = prices.price_id
WHERE categories.category_id = "28"
OR categories.category_id = "29"
OR categories.category_id = "30"
OR categories.category_id = "31"
OR categories.category_id = "32"
OR categories.category_id = "33"
OR categories.category_id = "34"
OR categories.category_id = "35"
AND from_sites.from_site_id =7
ORDER BY o.izdvojen, titles.title ASC
这里唯一的问题是忽略AND from_sites.from_site_id = 7。所以它列出了所有站点的所有子类。 但是,当我只使用一个category_id和from_site_id尝试同样的查询时,它就会起作用。
有人可以告诉我这里有什么问题吗?
答案 0 :(得分:4)
您需要使用括号明确告诉MySQL首先计算哪些子句。
试试这个:
WHERE (categories.category_id = "28"
OR categories.category_id = "29"
OR categories.category_id = "30"
OR categories.category_id = "31"
OR categories.category_id = "32"
OR categories.category_id = "33"
OR categories.category_id = "34"
OR categories.category_id = "35")
AND from_sites.from_site_id =7
或类似的东西,如果那不完全是你的意思。
答案 1 :(得分:1)
尝试使用括号来指示如何评估逻辑运算。
如果你想要任何列出的类别中的东西,除此之外,是from_site_id = 7,那么你的where部分应如下所示:
WHERE (
categories.category_id = "28"
OR categories.category_id = "29"
OR categories.category_id = "30"
OR categories.category_id = "31"
OR categories.category_id = "32"
OR categories.category_id = "33"
OR categories.category_id = "34"
OR categories.category_id = "35"
)
AND from_sites.from_site_id =7
您当前的查询是返回所有行,其中category_id = 28-34 OR来自类别35且来自SiteID = 7(因此除了categoryID 35之外,所有行都会忽略fromSiteID条件。)
答案 2 :(得分:0)
原始查询中似乎不需要很多东西。我可以建议一个简化版本吗?
SELECT title, category, image, url, description, from_site, price
FROM oglasi
LEFT JOIN titles USING (title_id)
LEFT JOIN categories USING (category_id)
LEFT JOIN images USING (image_id)
LEFT JOIN urls USING (url_id)
LEFT JOIN descriptions USING (description_id)
LEFT JOIN from_sites USING (from_site_id)
LEFT JOIN prices USING (price_id)
WHERE category_id IN (28,29,30,31,32,33,34,35) AND from_site_id =7
ORDER BY izdvojen, title