简体   繁体   中英

mysql query not returning desired results

I have three tables I am trying to pull results from but am turning up empty handed. Here is my query:

SELECT f . *, o . *, u.username, COUNT (o.order_id) as cnt 
FROM products f, orders o, users u 
WHERE f.product_id=o.product_id 
AND f.user_id = u.id 
AND (f.title LIKE '%hlt%' OR f.description LIKE '%hlt%' OR u.username LIKE '%hlt%') 
LIMIT 5

this is returning no results although there is definitely records that meet this criteria (although apparently not as I have it written).

You used COUNT (o.order_id) with out group BY .This is causing the problem.You can not execute this query with out using GROUP BY

GROUP BY

You need to use joins when pulling data from multiple tables. Your query should be:

SELECT f . *, o . *, u.username, COUNT (o.order_id) as cnt 
FROM products f
JOIN orders o ON f.product_id=o.product_id
JOIN users u ON f.user_id = u.id 
WHERE (f.title LIKE '%hlt%' OR f.description LIKE '%hlt%' OR u.username LIKE '%hlt%') 
LIMIT 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM