我有4张桌子:
艺术家:
id name
1 Band
2 DJ
流派:
id artist_id genre_id
1 1 2
2 1 3
3 2 2
分类
id artist_id category_id
1 1 1
2 1 2
3 2 3
价格:
id artist_id price time
1 1 120 60
1 1 400 240
我需要的是使用关键字在名称中搜索类型和类别。我需要最低的价格。
所以当我要求时:
关键字:" band" 类别:" 1" 类型:" 2"
结果应该是:
Band 120
还应按名称或价格订购。
我现在有这个,但是当它们有多个类别或类型时会返回多个艺术家。
SELECT * FROM artists
LEFT JOIN artists_genres ON artists_genres.artist_id = artists.id
LEFT JOIN artists_categories ON artists_categories.artist_id = artists.id
LEFT JOIN artists_prices ON artists_prices.artist_id = artists.id
WHERE genre_id = $genre AND category_id = $cat AND name LIKE '%$keyword%'
答案 0 :(得分:0)
尝试使用Group By
:
SELECT * FROM artists
LEFT JOIN artists_genres ON artists_genres.artist_id = artists.id
LEFT JOIN artists_categories ON artists_categories.artist_id = artists.id
LEFT JOIN artists_prices ON artists_prices.artist_id = artists.id
WHERE genre_id = $genre AND category_id = $cat AND name LIKE '%$keyword%'
GROUP BY artists.artists_id
答案 1 :(得分:0)
SELECT name,price FROM artists
LEFT JOIN artists_genres ON artists_genres.artist_id = artists.id
LEFT JOIN artists_categories ON artists_categories.artist_id = artists.id
LEFT JOIN artists_prices ON artists_prices.artist_id = artists.id
WHERE genre_id = $genre AND category_id = $cat AND name LIKE '%$keyword%'
GROUP BY artists_genres.artist_id ORDER BY name;
这当然会省略某些类别和类型,但可能足以满足您的需求
答案 2 :(得分:0)
你需要MIN功能,必须做一个GROUP BY artists.id:
SELECT MIN(artists_prices.price) as lowest_price * FROM artists
LEFT JOIN artists_genres ON artists_genres.artist_id = artists.id
LEFT JOIN artists_categories ON artists_categories.artist_id = artists.id
LEFT JOIN artists_prices ON artists_prices.artist_id = artists.id
WHERE genre_id = $genre AND category_id = $cat AND name LIKE '%$keyword%'
GROUP BY artists.id
答案 3 :(得分:0)
使用订单和限制只获得一条记录:
SELECT name,artists_prices.price FROM artists
LEFT JOIN artists_genres ON artists_genres.artist_id = artists.id
LEFT JOIN artists_categories ON artists_categories.artist_id = artists.id
LEFT JOIN artists_prices ON artists_prices.artist_id = artists.id
WHERE genre_id = $genre AND category_id = $cat AND name LIKE '%$keyword%'
ORDER BY artists_prices.price DESC
LIMIT 1