MYSQL / PHP:Concat返回LEFT JOIN上的许多字段

时间:2017-07-02 18:00:37

标签: php mysql join

我的SELECT查询LEFT JOIN根据需要运行。然后我通过一个smilar LEFT JOIN添加了一个表,现在我得到了一个奇怪的结果。基本上,对于group_concat我获得每个记录的一个项目,我得到了8个记录。我不知道为什么会发生这种情况,因为新表的连接与其他几个没有这个问题的连接类似(为了清楚起见,我在示例中省略了这一点)。

这是一个很好的查询:

$sql = "SELECT t.*, 
group_concat(tf.todoid) as `tftodoid`, 
group_concat(tf.id) as `tfid`, 
group_concat(tf.filedescript) as `tffiledescript`, 
group_concat(tf.filename) as `tffilename`, 
group_concat(tf.founderid) as `tffounderid`, 
group_concat(tf.ext) as `tfext`, 
group_concat(tf.lasttouched) as `tilt`
FROM titles `t`
LEFT JOIN titlefiles `tf` 
ON (tf.todoid = t.id AND tf.founderid = '$userid') 
WHERE t.userid='$userid' 
GROUP BY t.id";

这是带有额外联接的查询,现在正在泄漏项目的多个副本:

$sql = "SELECT t.*, 
group_concat(tf.todoid) as `tftodoid`, 
group_concat(tf.id) as `tfid`, 
group_concat(tf.filedescript) as `tffiledescript`, 
group_concat(tf.filename) as `tffilename`, 
group_concat(tf.founderid) as `tffounderid`, 
group_concat(tf.ext) as `tfext`, 
group_concat(tf.lasttouched) as `tilt`, 
group_concat(s.id) as `stepid`, 
group_concat(s.step) as `steps` 
FROM titles `t`
LEFT JOIN titlefiles `tf` 
ON (tf.titleid = t.id AND tf.founderid = '$userid') 
LEFT JOIN steps `s` 
ON s.titleid = t.id 
WHERE t.userid='$userid' 
GROUP BY t.id";

以下是JSON中输出的示例,显示了差异:

首先查询:

"tfid":"56,57,58,59,60,61,62,63,64,65,66,67,68,75,76,81"

第二次查询:

"tfid":"56,57,58,59,60,61,62,63,64,65,66,67,68,75,76,81,56,57,58,59,60,61,62,63,64,65,66,67,68,75,76,81,56,57,58,59,60,61,62,63,64,65,66,67,68,75,76,81,56,57,58,59,60,61,62,63,64,65,66,67,68,75,76,81,56,57,58,59,60,61,62,63,64,65,66,67,68,75,76,81,56,57,58,59,60,61,62,63,64,65,66,67,68,75,76,81,56,57,58,59,60,61,62,63,64,65,66,67,68,75,76,81,56,57,58,59,60,61,62,63,64,65,66,67,68,75,76,81,56,57,58,59,60,61,62,63,64,65,66,67,68,75,76,81",

我怀疑问题与JOIN或Group By语句有关但我无法查看如何修复。

如何确保每个文件只获得一个fileid而不是8个?

1 个答案:

答案 0 :(得分:1)

按如下方式更改该行:

group_concat(DISTINCT tf.id ORDER BY tf.id ASC) as `tfid`, 

这只会让你获得独特的ID。 如果你想要他们订购添加:

{{1}}