我有3个表,我想从中获取信息。
表
tblStaff
id |名称
tblWork
userid |周
tblOff
userid |周
例如,如果Michael在week
或tblWork
的{{1}}列中有值或多个值,那么我希望返回这些值。
更新
这个几乎可以按照我的意愿运作。除外,如果tblOff
和tblOff
如下所示:
Michael = userid 1
Dan = userid 2
tblWork
userid,周
1 | 2014年v47
1 | 2014 v50
2 | 2014 v48
tblOff
userid,周
1 | 2014 v48
1 | 2014 v49
2 | 2014 v52
然后我只在Michael的两个表中得到第一个结果,我没有得到tblWork
两个值。
week
SLOVED
这就是我所做的。在我使用explode()分隔值以将它们检查到当前年份+周
之后SELECT tblStaff.name as name, tblWork.week as work_week, tblOff.week as off_week
FROM tblStaff
LEFT JOIN tblWork
ON tblStaff.id = tblWork.userid
LEFT JOIN tblOff
ON tblStaff.id = tblOff.userid
GROUP BY tblStaff.name
答案 0 :(得分:0)
如果您的tblWork.week
列包含2014 v47
之类的值,那么
SELECT tblStaff.name as name,
GROUP_CONCAT(DISTINCT tblWork.week ORDER BY tblWork.week) as work_week
etc
会是这样的。
name work_week
Michael 2014 v47,2014 v48,2014 v50,2014 v51
George 2014 v49,2014 v50,2014 v51
GROUP_CONCAT
创建一个逗号分隔值的字符串。
如果你想要
name work_week
Michael 2014 v47 | 2014 v48 | 2014 v50 | 2014 v51
你需要
SELECT tblStaff.name as name,
GROUP_CONCAT(DISTINCT tblWork.week ORDER BY tblWork.week SEPARATOR ' | ') as work_week
您的php程序似乎并不期望文本字符串GROUP_CONCAT()
生成。
要为每个人的名字添加一行,其中包含工作周和周的列,您将需要这样的嵌套查询。
SELECT a.name, b.weeks as work_week, c.weeks as off_week
FROM tblStaff a
LEFT JOIN (
SELECT userid,
GROUP_CONCAT(DISTINCT week
ORDER BY week
SEPARATOR ' | ') as weeks
FROM tblWork
GROUP BY userid
) b ON a.id = b.userid
LEFT JOIN (
SELECT userid,
GROUP_CONCAT(DISTINCT week
ORDER BY week
SEPARATOR ' | ') as weeks
FROM tblOff
GROUP BY userid
) c ON a.id = c.userid
这是一个显示这个的SQL小提琴。 http://sqlfiddle.com/#!2/f63e0/1/0
您需要在GROUP BY
和tblWork
上单独执行tblOff
操作。如果你加入他们,然后进行GROUP BY
,你会得到组合爆炸,这是不好的。