在select和from子句中使用子查询的SQL错误

时间:2017-12-30 02:25:55

标签: mysql sql

我得到错误当我在select和from子句中使用子查询时 错误:https://www.awesomescreenshot.com/image/3069216/0505cad495528e9f9af2281ea281415c

到目前为止我做了什么:

library(data.table)

# Convert the data frame to data.table
setDT(intervals)
setDT(trips)

# Create a second column time2, which is the same as time
intervals[, time2 := time]

# Set keys in trips
setkey(trips, bike_id, start, finish)

# Conduct join by bike_id and time
# The columns in intervals used for join by time 
# needs to be in the last two in by.x
intervals2 <- foverlaps(intervals, trips, 
                        by.x = c("bike_id", "time", "time2"))

# Filter the ones with NA in start, which means no match
# And then selct the time and bike_id column
outcome <- intervals2[is.na(start)][, .(time, bike_id)] 
outcome

#                   time bike_id
#  1: 2017-11-22 16:00:03       2
#  2: 2017-11-22 16:30:02       2
#  3: 2017-11-22 16:40:03       2
#  4: 2017-11-22 16:50:02       2
#  5: 2017-11-22 17:00:02       2
#  6: 2017-11-22 17:10:02       2
#  7: 2017-11-22 17:20:03       2
#  8: 2017-11-22 17:30:03       2
#  9: 2017-11-22 16:30:02       3
# 10: 2017-11-22 17:20:03       3
# 11: 2017-11-22 17:30:03       3 

1 个答案:

答案 0 :(得分:1)

不确定你的查询中有什么不对,对我来说似乎没问题。但这是实现它的另一种方式。试试这个

SELECT m.id,
       m.title_name,
       m.release_date,
       m.plot,
       m.poster,
       t.count_user_rating
FROM   (SELECT u.*
        FROM   users u
               LEFT JOIN users_ratings ur
                      ON ur.user_id = u.id
        WHERE  ur.type_id = 2
               AND ur.type_name = 'movies') u
       LEFT JOIN users_ratings ur
              ON ur.user_id = u.id
       LEFT JOIN movies m
              ON m.id = ur.type_id
       LEFT JOIN (SELECT type_id,
                         Count(*) AS count_user_rating
                  FROM   users_ratings
                  WHERE  NAME = 'movies'
                  GROUP  BY type_id) t
              ON t.type_id = m.id
WHERE  ur.type_name = 'movies'
UNION
SELECT s.id,
       s.title_name,
       s.first_air_date release_date,
       s.plot,
       s.poster,
       t.count_user_rating
FROM   (SELECT u.*
        FROM   users u
               LEFT JOIN users_ratings ur
                      ON ur.user_id = u.id
        WHERE  ur.type_id = 2
               AND ur.type_name = 'movies') u
       LEFT JOIN users_ratings ur
              ON ur.user_id = u.id
       LEFT JOIN series s
              ON s.id = ur.type_id
       LEFT JOIN (SELECT type_id,
                         Count(*) AS count_user_rating
                  FROM   users_ratings
                  WHERE  NAME = 'series'
                  GROUP  BY type_id) t
              ON t.type_id = s.id
WHERE  ur.type_name = 'series'