MySQL - 结合单个结果查询&多结果查询到一个

时间:2014-01-29 01:35:27

标签: mysql select

我有以下2个查询:

这个表每个用户可以有多行(很多照片),我只想返回照片的数量/数量:

SELECT COUNT(*) FROM photos WHERE photo_description_profanity=1 AND photo_visible=1 AND photo_verified=1 AND userid='1000000002';

此表格仅为每位用户一个:

SELECT a.userid,a.profile_username,a.profile_gender,a.photo_name,a.photo_verified,b.profile_headline,
       YEAR(DATE_SUB(NOW(), INTERVAL TO_DAYS(a.profile_birthdate) DAY)) AS age,d.city,c.english AS country
FROM login AS a
JOIN `profiles` AS b ON a.userid=b.userid 
JOIN geoCountry AS c ON a.profile_country=c.countryCode
JOIN geoWorld AS d ON a.profile_geo_location=d.pid
WHERE a.userid IN ('1000000002','1000000003','1000000004');

是否可以合并这两个查询?

这是我的能力极限所以任何建议都会很棒:) thx

3 个答案:

答案 0 :(得分:1)

有可能。这需要两个步骤:

  • 将COUNT(*)调整为过滤SUM()
  • 将源表插入查询

SELECT a.userid,a.profile_username,a.profile_gender,a.photo_name,a.photo_verified,b.profile_headline,
       YEAR(DATE_SUB(NOW(), INTERVAL TO_DAYS(a.profile_birthdate) DAY)) AS age,d.city,c.english AS country

//Here we insert the count column
,IFNULL(SUM(IF(photo_description_profanity=1 AND photo_visible=1 AND photo_verified=1,1,0)),0) AS photocount

FROM login AS a
JOIN `profiles` AS b ON a.userid=b.userid 
JOIN geoCountry AS c ON a.profile_country=c.countryCode
JOIN geoWorld AS d ON a.profile_geo_location=d.pid

//Here we insert the source table
LEFT JOIN photos ON photos.userid=a.userid

WHERE a.userid IN ('1000000002','1000000003','1000000004')

//Group by users
GROUP BY a.userid

答案 1 :(得分:1)

如果您希望将此作为附加列,请将其交叉连接到结果中:

select const.cnt, . . . 
from (SELECT COUNT(*) as cnt
      FROM photos
      WHERE photo_description_profanity=1 AND photo_visible=1 AND
            photo_verified=1 AND userid='1000000002'
     ) const cross join
     login AS a
     JOIN `profiles` AS b ON a.userid=b.userid 
     JOIN geoCountry AS c ON a.profile_country=c.countryCode
     JOIN geoWorld AS d ON a.profile_geo_location=d.pid
//Here we insert the source table
     LEFT JOIN photos ON photos.userid=a.userid
WHERE a.userid IN ('1000000002','1000000003','1000000004');

使用cross join而不是嵌套选择查询的优点是性能。 MySQL将为返回集中的每一行执行嵌套选择。在from子句中,它只会被执行一次。

答案 2 :(得分:1)

SELECT
    a.userid,
    a.profile_username,
    a.profile_gender,
    a.photo_name,
    a.photo_verified,
    b.profile_headline,
    YEAR(DATE_SUB(NOW(), 
    INTERVAL TO_DAYS(a.profile_birthdate) DAY)) AS age,
    d.city,c.english AS country,
    (SELECT COUNT(*) FROM photos WHERE photo_description_profanity=1 AND photo_visible=1 AND photo_verified=1 AND userid= a.userid) AS result_count
FROM login AS a
JOIN `profiles` AS b ON a.userid=b.userid 
JOIN geoCountry AS c ON a.profile_country=c.countryCode
JOIN geoWorld AS d ON a.profile_geo_location=d.pid
WHERE a.userid IN ('1000000002','1000000003','1000000004');