简体   繁体   English

从另一个连接到php时,表上的Mysql concat列

[英]Mysql concat column on table while joining from another to php

Here's the basic layout:这是基本布局:

Table1:
    id 10, blah
    id 11, test
Table2: 
    id 1, 10, some info
    id 2, 10, more info
    id 3, 11, more info

What query using sql would allow me to display the results like so, when using php and mysql_fetch_object:当使用 php 和 mysql_fetch_object 时,使用 sql 的查询将允许我显示这样的结果:

10, blah, more info, some info
11, test, more info

Right now, I have:现在,我有:

select * from table1
join (table2, table3)
on (table2.id = table1.id and table3.id = table1.id)

The problem with this is that I get multiple result rows for the same id because of the multiple values in tables 2 and 3.这样做的问题是,由于表 2 和表 3 中的多个值,我得到了相同 ID 的多个结果行。

EDIT: I got it to work!编辑:我让它工作了!

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's got the group_concat function for this, though it is internally limited to a default of 1024 characters, so you can't make arbitrarily large strings with it: 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

If your string ends up being "large", you might be better off pulling the data in seperate queries and doing the concatenation in PHP.如果您的字符串最终变得“大”,您最好在单独的查询中提取数据并在 PHP 中进行连接。

If you only need a few certain columns, only select those columns (rather than SELECT * ), and use DISTINCT .如果您只需要几个特定的​​列,只需选择这些列(而不是SELECT * ),并使用DISTINCT eg: SELECT DISTINCT id, col, col FROM ...例如: SELECT DISTINCT id, col, col FROM ...

The DISTINCT keyword will make sure only unique rows are returned. DISTINCT关键字将确保只返回唯一的行。 If even one value is different, however, it's not unique and another row will be returned.但是,即使一个值不同,它也不是唯一的,将返回另一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM