我试图设置JOIN,我的LISTINGS表在LISTING_META表中有META,这些列表表示为汽车。
当我搜索1994 - 2014年的汽车而且这是一个特定的品牌时,我没有得到任何结果,我想要做的是能够返回META值与正确的年份和品牌相匹配的列表吗?未来发动机尺寸,cc等。
我不知道最好的方法,但这是我当前的查询:
SELECT * FROM listing
LEFT JOIN listing_meta AS l_meta ON l_meta.auction = listing.id
WHERE status = '1' AND cat_id IN (24,25,26,27,28,29,30)
AND (((l_meta.field = 'year' AND l_meta.value >= 1994) OR (l_meta.field = 'year' AND l_meta.value <= 2014)) AND (l_meta.field = 'brand' AND l_meta.value = '2'))
AND price_start >= 0 AND price_start <= 999999
AND time_end >= 1413347572 AND time_start <= 1413347572
ORDER BY opt_highlight DESC, id DESC
LIMIT 0,9
我在考虑做EXISTS,但这可能有点沉重......有什么简单的东西吗?感谢帮助。
答案 0 :(得分:3)
如果要匹配listing_meta
表中的多行,则需要多次加入。
SELECT *
FROM listing AS l
INNER JOIN listing_meta AS m1 ON m1.auction = l.id
INNER JOIN listing_meta AS m2 ON m2.auction = l.id
WHERE l1.field = 'year' AND l1.value BETWEEN 1994 AND 2014
AND l2.field = 'brand' AND l2.value = '2'
AND price_start BETWEEN 0 AND 999999
AND time_end BETWEEN 1413357572 AND 1413347572
ORDER BY opt_highlight DESC, id DESC
LIMIT 0, 9
您也应该使用INNER JOIN
,而不是LEFT JOIN
;如果希望结果包含不匹配的行,请使用LEFT JOIN
。