MySQL计数元素而不使用count(*)

时间:2016-07-08 08:01:48

标签: mysql count

我正在为即将到来的考试练习MySQL,需要一些帮助。

我有这个db:
用户(代码,姓名,姓氏,年龄)
剧院(名称,城市,容量)
订阅(ID,UserCode,TheatreName,Amount)

使用这些参照完整性约束:

SUBSCRIPTION.UserCode-> USER.Code
SUBSCRIPTION.TheatreName-> THEATRE.Name

对于练习,我需要编写一个查询,该查询确定50岁以上用户的代码,姓名和姓氏,并且有多个订阅但没有使用COUNT函数。
我知道也许自我加入可能有所帮助,但我真的不知道如何。谁能帮我?非常感谢你。

2 个答案:

答案 0 :(得分:1)

您可以使用

 EXISTS

SELECT u.Code, u.Name, u.Surname
FROM USER u
WHERE u.Age > 50
AND EXISTS (
    SELECT 1 FROM SUBSCRIPTION s WHERE u.Code = s.UserCode
)

JOIN

SELECT DISTINCT u.Code, u.Name, u.Surname
FROM USER u
JOIN SUBSCRIPTION s
ON u.Code = s.UserCode
WHERE u.Age > 50

<强> 编辑:

SELECT DISTINCT u.Code, u.Name, u.Surname
FROM USER u
JOIN SUBSCRIPTION s1
ON u.Code = s1.UserCode
JOIN SUBSCRIPTION s2
ON u.Code = s2.UserCode
WHERE s1.ID <> s2.ID
AND u.Age > 50

答案 1 :(得分:1)

我认为实现这一目标的最简单方法是将count函数重新设计为带有case语句的sum函数:

SELECT
  u.NAME
, u.SURNAME
, u.CODE
, SUM(CASE WHEN t.SUBSCRIPTION IS NOT NULL THEN 1 ELSE 0 END) as TOTAL_SUBSCRIPTIONS -- IDENTICAL TO COUNT(s.*)
, COUNT(s.*) -- SHOULD MATCH THE TOTAL_SUBSCRIPTIONS
FROM
USER AS u
LEFT JOIN SUBSCRIPTION AS s
ON  u.CODE = s.USERCODE
-- LEFT JOIN THEATRE AS t -- commented because I don't see a requirement for this table to be brought forward.
-- ON  s.THEATRENAME = t.NAME
WHERE u.AGE > 50
HAVING SUM(CASE WHEN t.SUBSCRIPTION IS NOT NULL THEN 1 ELSE 0 END) > 1

不使用CASE声明:

SELECT
      u.NAME
    , u.SURNAME
    , u.CODE
    , SUM( (select SUM(1) from SUBSCRIPTION WHERE s.USERCODE = u.CODE) ) as TOTAL_SUBSCRIPTIONS -- IDENTICAL TO COUNT(s.*)
    FROM
    USER AS u
    WHERE u.AGE > 50