1

很抱歉这个简单的问题,但查看了一些旧问题,找不到我需要的答案。

我有 3 个带有 user_id 的表(尽管每个表中的名称不同),我想将它们与每个表中的条件连接在一起。我之前只对 2 个表进行了 JOIN,并且很好奇为什么我的下面的查询会引发错误。

SELECT c.user_id FROM
    (SELECT userid from database_all where date='2013-09-03' AND college='Harvard') a
JOIN
    (SELECT userid2 FROM database_users) b
ON 
    a.userid = b.userid2
JOIN
    (SELECT user_id FROM database_courses where num_courses < 3 ) c
ON 
    b.userid2 = c.user_id
4

3 回答 3

2

此查询应该可以解决您的问题:

SELECT 
    database_courses.user_id 
FROM 
    database_all 
JOIN
    database_users  ON database_all.userid=database_users.userid2
JOIN
    database_courses  ON database_users.userid2=database_courses.userid
WHERE
    database_all.date='2013-09-03' AND database_all.college='Harvard' AND database_courses.num_courses < 3
于 2013-09-05T00:22:30.440 回答
0

尝试更多类似的东西:

SELECT c.user_id FROM database_all AS a 
JOIN database_users AS u ON a.userid=u.userid2
JOIN database_courses AS c ON b.userid2=c.user_id
WHERE a.data='2013-09-03' 
AND a.college='Harvard'
AND c.num_courses<3

通常你需要把你的WHERE子句放在最后,它DBMS会为你优化查询。

我实际上在这里有一个非常相似的问题。

MySQL 文档在其关于SELECT语法的部分也对此进行了介绍。

SELECT
    [ALL | DISTINCT | DISTINCTROW ]
      [HIGH_PRIORITY]
      [STRAIGHT_JOIN]
      [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
      [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
    select_expr [, select_expr ...]
    [FROM table_references
    [WHERE where_condition]
    [GROUP BY {col_name | expr | position}
      [ASC | DESC], ... [WITH ROLLUP]]
    [HAVING where_condition]
    [ORDER BY {col_name | expr | position}
      [ASC | DESC], ...]
    [LIMIT {[offset,] row_count | row_count OFFSET offset}]
    [PROCEDURE procedure_name(argument_list)]
    [INTO OUTFILE 'file_name' export_options
      | INTO DUMPFILE 'file_name'
      | INTO var_name [, var_name]]
    [FOR UPDATE | LOCK IN SHARE MODE]]

如您所见,FROM带有表引用的子句直接位于WHERE子句之前。

于 2013-09-05T00:26:31.463 回答
0

或者

Select distinct u.user_id -- I think you might not want the same userId repeated ???
From database_users u 
   join database_courses c
      On c.userId = u.UserId
         And c.num_courses < 3
   join database_all a
      On a.UserId = u.UserId
         And a.date='2013-09-03' 
         And a.college='Harvard'
于 2013-09-05T00:32:05.680 回答