我正在准备一个MySQL全文搜索应用程序。
我有两个表:Books
和Price
。我需要在搜索执行时从两个表中获取数据。
Books
架构:
id,name,title,active
1,Alex, Alex Bio,1
2,Bob, Bob Bio, 1
mysql fulltext index(name,title)
Price
架构:
id,product_id,price
1,1,500
2,1,600
3,1,700
4,2,300
5,2,400
6,2,500
当我运行以下查询时,搜索工作正常,但我需要price
;并且只有最低price
应与product_id
一起显示。
以下是我的完整查询:
SELECT *,
MATCH (name, title)
AGAINST ('" . $search . "' IN BOOLEAN MODE) AS "high"
FROM books
WHERE MATCH (name, title) AGAINST ('" . $search . "' IN BOOLEAN MODE)
AND active = 1
ORDER BY high DESC;
预期产出:
id,name,title,price
1,Alex,Alex Bio,500
2,Bod,Bob Bio,300
答案 0 :(得分:2)
您需要加入才能完成这项工作:
SELECT t1.id, t1.name, t1.title, COALESCE(t2.minPrice, 'NA') AS price
FROM books t1
LEFT JOIN
(
SELECT product_id, MIN(price) AS minPrice
FROM price
GROUP BY product_id
) t2
ON t1.id = t2.product_id
WHERE MATCH (name,title) AGAINST ('" . $search . "' IN BOOLEAN MODE) AND active = 1
ORDER BY MATCH (name,title) AGAINST ('" . $search . "' IN BOOLEAN MODE) DESC
答案 1 :(得分:1)
只需将价格表加入书籍,获得最低价格并添加group by子句:
SELECT books.id, name, title, min(p.price)
FROM books
INNER JOIN price p on p.product_id=books.id
WHERE MATCH (name,title) AGAINST ('" . $search . "' IN BOOLEAN MODE) AND active = 1
GROUP BY books.id, name, title
ORDER BY MATCH (name,title) AGAINST ('" . $search . "' IN BOOLEAN MODE) DESC