如何在SQL中嵌套select语句?

时间:2010-01-13 17:37:49

标签: sql mysql

我正在尝试只选择第一个select语句和最后一个select语句中的User_IDs,但我做错了。

SELECT COUNT(DISTINCT User_ID) AS total
FROM UserClicks
WHERE (Date > :startDate AND Date < :endDate) 
AND User_ID IN (
    SELECT User_ID 
    FROM UserClicks
    WHERE (Date > :monthBeforeStartDate AND Date < :startDate)
)

更新:这是针对MySQL数据库的。

5 个答案:

答案 0 :(得分:2)

子查询和加入适合您

SELECT DISTINCT u1.UserID 
FROM
  UserClicks u1
INNER JOIN
(
   SELECT 
      UserID 
   FROM 
     UserClicks 
   WHERE 
     (Date > :monthBeforeStartDate AND Date < :startDate)
) u2
ON u1.UserID = u2.UserID
WHERE
  (u1.Date > :startDate AND u1.Date < :endDate)

答案 1 :(得分:0)

如果你的查询挂起,那是因为索引,为了优化外部查询和内部查询,你需要像这样的索引:

create index du on UserClicks (Date, User_ID)
create index ud on UserClicks (User_ID, Date)

它应该立即返回。有关mysql如何优化使用IN运算符指定的子查询的更多详细信息:

http://dev.mysql.com/doc/refman/5.1/en/optimizing-subqueries.html

  

MySQL取代了子查询   跟随索引查找的表单   函数,EXPLAIN描述为   特殊连接类型(unique_subquery或   index_subquery):

     

... IN(SELECT indexed_column FROM   single_table ...)

答案 2 :(得分:0)

SELECT COUNT(DISTINCT User_ID) AS total
    FROM UserClicks
    WHERE (Date BETWEEN startDate AND endDate) AND User_ID IN ( 
        SELECT User_ID 
        FROM UserClicks
        WHERE (Date BETWEEN monthBeforeStartDate AND startDate)
    ) GROUP BY User_ID 

答案 3 :(得分:0)

我很好奇......你为什么不在这里发表更详细的陈述?

SELECT COUNT(DISTINCT User_ID) AS total
FROM UserClicks
WHERE (Date > :startDate AND Date < :endDate)
AND (Date > :monthBeforeStartDate AND Date < :startDate)

更新:
您似乎想要计算在startDate之前点击的startDate和endDate之间点击的用户数量。

根据您的日期是否为MySQL友好格式(如YYYY-MM-DD HH:MM:SS),您可以使用MySQL获取开始日期之前的月份。示例如下:

SELECT COUNT(DISTINCT User_ID) AS total
FROM UserClicks
WHERE (Date > :startDate AND Date < :endDate)
AND (Date > DATE_SUB(:startDate, INTERVAL 1 MONTH) AND Date < :startDate)

答案 4 :(得分:0)

我在mysql中使用子查询很困难,其中两个查询都使用相同的表。我的解决方案一直是使用连接

SELECT COUNT(DISTINCT User_ID) AS total
FROM UserClick u1 
    JOIN UserClick u2 
        on u2.User_ID = u1.User_ID
WHERE u1.Date BETWEEN :startDate AND :endDate
    AND u2.Date BETWEEN :monthBeforeStartDate and :startDate