我有两张桌子。
第二个表格中每个nid
有多个cid
。我想要做的是在临时列或表中折叠查询中的数据,如示例中所示。
biblio_contributor_data
+-----+----------+-----------+ | cid | lastname | firstname | +-----+----------+-----------+ | 1 | john | grand | | 2 | James | cook | | 3 | marco | palo | +-----+----------+-----------+
biblio_contributor
+-----+------+ | nid | cid | +-----+------+ | 4 | 1 | | 4 | 2 | | 4 | 3 | | 5 | 2 | +-----+------+
如果可能的话,如果可能的话,我希望查询结果如下:
+-----+------------------------------------+ | nid | temporary column | +-----+------------------------------------+ | 4 | john grand, James cook, marco palo | | 5 | James cook | +-----+------------------------------------+
答案 0 :(得分:1)
使用CONCAT
合并lastname
和firstname
,并使用GROUP_CONCAT
组合不同的行。
<强>查询强>
SELECT t1.nid,
GROUP_CONCAT(CONCAT(t2.lastname,' ',t2.firstname)) AS `temporary column`
FROM biblio_contributor t1
JOIN biblio_contributor_data t2
ON t1.cid=t2.cid
GROUP BY t1.nid;
答案 1 :(得分:0)
试试这个
SELECT b1.nid, group_concat(concat(firstname, " ", lastname))
from biblio_contributor b1, biblio_contributor_data b2 ON b1.cid=b2.cid
group by b1.nid
答案 2 :(得分:0)
以下对我有用:
<?php
$stmt = 'SELECT t2.nid, group_concat(t1.lastname, t1.firstname) FROM `biblio_contributor_data` as t1 INNER JOIN biblio_contributor as t2 GROUP BY t2.nid';
$res = mysql_query($stmt);
while($rp = mysql_fecth_array($res)) {
// YOUR LOGIC GOES HERE
}
?>
答案 3 :(得分:0)
直到现在还没有人投入GROUP_CONCAT的手册页,这里是:
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
请好好读一读,尤其是
部分结果被截断为group_concat_max_len系统变量给出的最大长度