如何从主查询中选择结果到子查询中

时间:2013-01-16 11:54:28

标签: mysql sql select subquery

  

可能重复:
  how to select count from main query into subquery

我想将主查询中选择的记录数量提取到子查询中

我当前正在尝试执行的查询是:

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

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT
    cat_id,
    category_name,
    seo_name,
    (
        SELECT COUNT(category_name)
        FROM ccs_coupons c2 
        WHERE c2.category_name LIKE CONCAT('%', c1.category_name, '%')
           OR c2.website_name LIKE CONCAT('%', c1.category_name, '%')
           OR c2.description LIKE CONCAT('%', c1.category_name, '%')
           OR c2.url_desc LIKE CONCAT('%', c1.category_name, '%')
    )  AnyAlias 
FROM  `ccs_coupons` c1 
WHERE  category_name LIKE 'a%'
GROUP BY category_name
ORDER BY category_name ASC
LIMIT $page,$config

答案 1 :(得分:0)

你可以尝试:

SELECT 
  a.cat_id
  ,a.category_name
  ,a.seo_name
  ,count(b.cat_id) as count
FROM 
  ccs_coupons as a
  INNER JOIN ccs_coupons as b
  ON  website_name = category_name
         OR description = category_name
         OR url_desc = category_name
WHERE 
  category_name like 'a%' 
GROUP BY 
  a.cat_id
  ,a.category_name
  ,a.seo_name 
ORDER BY 
  category_name ASC 
LIMIT 
  $page,$config

虽然我不是100%确定你要做什么..你可能需要在做计数之前做一些独特的约束