这是基本布局:
Table1:
id 1o, 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
答案 0 :(得分:1)
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中进行连接。
答案 1 :(得分:0)
如果您只需要几个特定列,则只需选择这些列(而不是SELECT *
),然后使用DISTINCT
。例如:SELECT DISTINCT id, col, col FROM ...
DISTINCT
关键字将确保仅返回唯一行。但是,即使一个值不同,它也不是唯一的,而是会返回另一行。