在mysql中通过id连接两个表

时间:2014-09-17 14:29:26

标签: mysql

我有两张这样的表:

Table_users
id | firstname | lastname
1  | John      | Doe
2  | Eve       | Adam


table_shifts
date       | dayshift | nightshift
2014-09-17 | 1        | 2
2014-09-18 | 2        | 1

我希望这样做:

table_shifts_overview
date       | dayshift | nightshift
2014-09-17 | John Doe | Eve Adam

where date ='2014-09-17'

我尝试使用JOIN和子查询,但它没有成功。任何挫折都会受到赞赏。

5 个答案:

答案 0 :(得分:1)

尝试此查询

SELECT TS.date, CONCAT(TU1.firstname,' ', TU1.lastname) AS dayshift, CONCAT(TU2.firstname, ' ', TU2.lastname) AS nightshift 
FROM table_shifts TS
INNER JOIN table_users TU1 on TU1.ID= TS.dayShift 
INNER JOIN table_users TU2 on TU2.id= TS.NightShift 
WHERE TS.Date = '2014-09-17'

答案 1 :(得分:0)

您可以通过别名来多次加入同一个表:

SELECT date, u1.firstname, u1.lastname, u2.firstname, u2.lastname
FROM table_shifts
INNER JOIN table_users AS u1 ON u1.id = dayshift.id
INNER JOIN table_users AS u2 ON u2.id = nightshift.id

答案 2 :(得分:0)

SELECT S.date, 
       concat(U1.FirstName,' ', U1.LastName) dayshift, 
       concat(U2.FirstName,' ', U2.LastName) nightshift
FROM table_Shifts S
INNER JOIN table_users U1 
  on U1.ID= S.dayShift
INNER JOIn table_users U2 
  on U2.id= S.NightShift
WHERE S.Date = '2014-09-17'

答案 3 :(得分:0)

您可以使用隐式联接:

SELECT s.date,
    CONCAT(u_day.firstname, ' ', u_day.lastname) AS dayshift,
    CONCAT(u_night.firstname, ' ', u_night.lastname) AS nightshift
FROM shifts s, users u_day, users u_night
WHERE s.dayshift = u_day.id AND s.nightshift = u_night.id
AND s.date = '2014-09-17'

或明确加入:

SELECT s.date,
    CONCAT(u_day.firstname, ' ', u_day.lastname) AS dayshift,
    CONCAT(u_night.firstname, ' ', u_night.lastname) AS nightshift
FROM shifts s
    INNER JOIN users u_day ON (s.dayshift = u_day.id)
    INNER JOIN users u_night ON (s.nightshift = u_night.id)
WHERE s.date = '2014-09-17'

请注意,关键字INNER在上一个查询中是可选的。

以下是有关JOIN语法的MySQL文档: http://dev.mysql.com/doc/refman/5.6/en/join.html

答案 4 :(得分:0)

你可以试试;

SELECT ts.date, 
    contact(tu.firstname ,' ', tu.lastname) AS dayshift,
    contact(tu2.firstname ,' ', tu2.lastname) AS nightshift
FROM table_shifts ts, Table_users tu, Table_users tu2 
   WHERE ts.dayshift = tu.id AND
         ts.nighshift = tu2.id AND
         ts.date = '2014-09-17'