MySQL查询,您无法通过联接访问关系

时间:2014-04-09 10:34:44

标签: mysql sql join left-join inner-join

我有以下MySQL表:

+--------------------+----------+------+-----+---------+----------------+
| Field              | Type     | Null | Key | Default | Extra          |
+--------------------+----------+------+-----+---------+----------------+
| id                 | int(11)  | NO   | PRI | NULL    | auto_increment |
| firstName          | longtext | NO   |     | NULL    |                |
| lastName           | longtext | NO   |     | NULL    |                |
| username           | longtext | NO   |     | NULL    |                |
+--------------------+----------+------+-----+---------+----------------+

+------------------------+----------+------+-----+---------+----------------+
| Field                  | Type     | Null | Key | Default | Extra          |
+------------------------+----------+------+-----+---------+----------------+
| id                     | int(11)  | NO   | PRI | NULL    | auto_increment |
| trainee_id             | int(11)  | NO   | MUL | NULL    |                |
| date                   | date     | NO   |     | NULL    |                |
| duration               | time     | NO   |     | NULL    |                |
| educationDepartment    | longtext | NO   |     | NULL    |                |
| completedtasks         | longtext | NO   |     | NULL    |                |
+------------------------+----------+------+-----+---------+----------------+

我有两个条件。我从第二个表开始和结束日期,我想要一个特定用户的数据,我可以通过"用户名"第一张桌子。它看起来像这样:用户名已知>我将获得用户的id(外键)>现在,我可以使用此外键从第二个表中获取用户特定的数据。我开始我的MySQL查询,它看起来像这个atm:

SELECT date, duration, educationDepartment, completedtasks FROM programm_completedtask WHERE date BETWEEN "2014-04-07" AND "2014-04-11";

但是我现在如何才能使用它?重要提示:我只想要一个MySQL查询,php或类似的东西不能帮助我:/

3 个答案:

答案 0 :(得分:1)

这样的东西?

SELECT table2.username, table1.date, table1.duration, table1.educationDepartment, table1.completedtasks FROM table1 LEFT JOIN table2 ON table2.id = table1.trainee_id WHERE table1.date BETWEEN "2014-04-07" AND "2014-04-11" AND table1.username = 'someuser';

答案 1 :(得分:1)

这会将结果限制为一个特定用户:

SELECT date, duration, educationDepartment, completedtasks 
FROM programm_completedtask 
WHERE date BETWEEN '2014-04-07' AND '2014-04-11'
AND trainee_id = (select id from users where username = 'XYZ');

答案 2 :(得分:1)

如果您想从两个表中获得结果,您应该使用INNER JOIN

SELECT u.username, p.date, p.duration, p.educationDepartment, p.completedtasks 
FROM programm_completedtask AS p
INNER JOIN users AS u ON u.id = p.trainee_id
WHERE date BETWEEN "2014-04-07" AND "2014-04-11"
AND u.username = "knownusername";