在sql中加入四个以上的表

时间:2016-04-07 13:58:26

标签: mysql

我有以下表格,其中包含以下列:http://sqlfiddle.com/#!2/8776a0/2

中的更多内容
request : {id,request_id, client_id, product_name, designation_date_1, can }
assigned_samples:{id,labref, user_id, stat}
users{id, fname, lname}
clients:{id, name}
tracking_table{labref, activity, added_date}

我想要做的是加入所有这些表,并提出一个包含所有数据的大表 当加入跟踪表时,条件是检查活动列是否给出了值" a", 如果找不到匹配的行,则date_added应为null,否则显示date_added

result table {labref, prod, desc_date, can, CONCAT(fname,' ',lname), date_added}

SELECT r.request_id, r.product_name, r.can, r.designation_date_1, CONCAT(u.fname,' ', u.lname) as analyst, a_s.stat
FROM request r, assigned_samples a_s, user u, clients c
WHERE r.client_id=c.id
AND a_s.analyst_id = u.id
AND r.request_id = a_s.labref
AND r.client_id='2'
GROUP BY r.request_id

如果我在查询中添加一个条件,它会返回数据,但是date_added都是相同的,这是错误的

SELECT r.request_id, r.product_name, r.can, r.designation_date_1, CONCAT(u.fname,' ', u.lname) as analyst, a_s.stat
FROM request r, assigned_samples a_s, user u, clients c, tracking_table t
WHERE r.client_id=c.id
AND a_s.analyst_id = u.id
AND r.request_id = a_s.labref
AND t.activity ='Authorizing COA Release'
AND r.client_id='2'
GROUP BY r.request_id

1 个答案:

答案 0 :(得分:1)

应为join condition添加

tracking_table

试试这个:

<强> SQLFiddle: http://sqlfiddle.com/#!2/3a116f/1

(我稍微更改了演示的输入数据)

SELECT r.request_id, r.product_name, r.can, r.designation_date_1, CONCAT(u.fname,' ', u.lname) as analyst, a_s.stat,
  date_added
FROM request r, assigned_samples a_s, user u, clients c, tracking_table t
WHERE r.client_id=c.id
AND a_s.analyst_id = u.id
AND r.request_id = a_s.labref
AND r.client_id='2'
AND r.request_id = t.labref
AND t.activity ='Authorizing COA Release'