count()来自不同表的where子句

时间:2012-12-31 03:15:45

标签: sql

我有一个搜索功能,可以根据输入搜索mysql结果。现在我想在where子句中包含来自不同表格的结果的count()。

喜欢这个场景。 I want to search "Dog" where count(like_id) >= 1.

我想要包括的喜欢表格是:TABLE_GLOBAL_LIKES

TABLE_GLOBAL_LIKES的结构是: 字段:like_iduser_idproducts_idblog_id

两个TABLE_GLOBAL_PRODUCTSTABLE_GLOBAL_LIKES共有一个products_idblog_id的公共字段。

这是我的工作查询,我希望包含Likes表。

SELECT SQL_CALC_FOUND_ROWS p.*,
       CASE
           WHEN p.specials_new_products_price > 0.0000
                AND (p.expires_date > Now()
                     OR p.expires_date IS NULL
                     OR p.expires_date ='0000-00-00 00:00:00')
                AND p.status != 0 THEN p.specials_new_products_price
           ELSE p.products_price
       END price
FROM ".TABLE_GLOBAL_PRODUCTS." p
INNER JOIN ".TABLE_STORES." s ON s.blog_id = p.blog_id
WHERE MATCH (p.products_name,
             p.products_description) AGAINST ('*".$search_key."*')
  AND p.display_product = '1'
  AND p.products_status = '1' HAVING price <= ".$priceto_key."
  AND price >= ".$pricefrom_key."
ORDER BY p.products_date_added DESC, p.products_name

我是mysql查询的新手..请帮忙。

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT SQL_CALC_FOUND_ROWS p.*, COUNT(l.like_id)
       CASE
           WHEN p.specials_new_products_price > 0.0000
                AND (p.expires_date > Now()
                     OR p.expires_date IS NULL
                     OR p.expires_date ='0000-00-00 00:00:00')
                AND p.status != 0 THEN p.specials_new_products_price
           ELSE p.products_price
       END price
FROM ".TABLE_GLOBAL_PRODUCTS." p
INNER JOIN ".TABLE_STORES." s ON s.blog_id = p.blog_id
INNER JOIN ".TABLE_GLOBAL_LIKES." l ON l.blog_id = p.blog_id AND l.products_id = p.products_id
WHERE MATCH (p.products_name,
             p.products_description) AGAINST ('*".$search_key."*')
  AND p.display_product = '1'
  AND p.products_status = '1' HAVING price <= ".$priceto_key."
  AND price >= ".$pricefrom_key."
GROUP BY p.products_id
HAVING COUNT(l.like_id)>0
ORDER BY p.products_date_added DESC, p.products_name