这是基本布局:
Table1:
id 10, blah
id 11, test
Table2:
id 1, 10, some info
id 2, 10, more info
id 3, 11, more info
当使用 php 和 mysql_fetch_object 时,使用 sql 的什么查询可以让我显示这样的结果:
10, blah, more info, some info
11, test, more info
现在,我有:
select * from table1
join (table2, table3)
on (table2.id = table1.id and table3.id = table1.id)
这样做的问题是,由于表 2 和 3 中存在多个值,我获得了同一 ID 的多个结果行。
编辑:我让它工作了!
select table1.id, group_concat(table2.data), table3.data
from table1
join (table2, table3)
on (table2.id = table1.id and table3.id = table1.id)
group by table1.id
最佳答案
MySQL 有 group_concat函数用于此目的,尽管它在内部限制为默认的 1024 个字符,因此您不能用它创建任意大的字符串:
SELECT table1.id, CONCAT(table1.data, GROUP_CONCAT(table2.data))
FROM table1
LEFT JOIN table2 ON table1.id = table2.table1_ID
GROUP BY table1.id
如果您的字符串最终变得“很大”,您最好在单独的查询中提取数据并在 PHP 中进行串联。
关于php - Mysql 在表上连接列,同时从另一个连接到 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3944598/