2013-01-16 71 views
-2

我想要得到的是在主查詢選擇成我目前正在執行的子查詢如何選擇主查詢次數爲子查詢

查詢記錄數:

SELECT cat_id,category_name,seo_name,(SELECT count(category_name) FROM ccs_coupons WHERE (category_name LIKE category_name OR website_name LIKE category_name OR description LIKE LIKE category_name OR url_desc LIKE category_name)) FROM `ccs_coupons` WHERE category_name like 'a%' GROUP BY category_name ORDER BY category_name ASC LIMIT $page,$config 

回答

0

你可以只使用兩個表,而不是相關子查詢之間的連接:

SELECT c.id, 
    u.display_name, 
    c.comments_count 
FROM users u 
LEFT JOIN 
(
    SELECT COUNT(*) comments_count, author_id 
    FROM cms_comments 
    GROUP BY author_id 
) c 
    ON c.author_id = u.id 
WHERE c.comments_count > 150; 

編輯,根據您的更新,你仍然應該能夠使用這樣的事情:

SELECT c1.cat_id, 
    c1.category_name, 
    c1.seo_name, 
    c2.CountCategoryName 
FROM `ccs_coupons` c1 
LEFT JOIN 
(
    SELECT count(category_name) CountCategoryName, category_name, 
     website_name, description, url_desc 
    FROM ccs_coupons 
    GROUP BY category_name 
) c2 
    on c2.category_name LIKE c1.category_name 
    or c2.website_name LIKE c1.category_name 
    or c2.description LIKE c1.category_name 
    or c2.url_desc LIKE c1.category_name 
WHERE c1.category_name like 'a%' 
ORDER BY c1.category_name ASC 
LIMIT $page,$config; 

甚至使用:

SELECT c1.cat_id, 
    c1.category_name, 
    c1.seo_name, 
    count(c2.category_name) 
FROM `ccs_coupons` c1 
INNER JOIN ccs_coupons c2 
    on c2.category_name LIKE c1.category_name 
    or c2.website_name LIKE c1.category_name 
    or c2.description LIKE c1.category_name 
    or c2.url_desc LIKE c1.category_name 
WHERE c1.category_name like 'a%' 
GROUP BY c1.category_name 
ORDER BY c1.category_name ASC 
LIMIT $page,$config; 
+0

@SahilAgarwal我不知道我完全理解你的編輯,但我已經更新了我的答案。 – Taryn

0

你不能把HAVING子句外部查詢,因爲它是不是彙總查詢。試試這個:

SELECT users.id, 
     users.display_name, 
     COUNT(*) AS comments_count 
    FROM users 
    INNER JOIN cms_comments 
    ON users.id = cms_comments.author_id 
GROUP BY users.id, users.display_name 
HAVING COUNT(*) > 150;