简体   繁体   English

在mysql中使用select join时将数据选择为单行

[英]Selecting data as a single row when using select join in mysql

How can I get data from a mysql query in a single row when selecting data from two tables using a join? 使用联接从两个表中选择数据时,如何从mysql查询的一行中获取数据?

"id"    "itemId"    "itemTempId"    "itemName"                  "userId" "postId"
"1"     "US1"       "T001"          "Samsung Galaxy Note 5"     "1"      "1"

"id"    "itemId"    "itemTempId"    "itemImageName"     "userId" "postId"
"1"     "US1"       "T001"          "front.jpg"         "1"      "1"
"2"     "US1"       "T001"          "side-left.jpg"     "1"      "1"
"3"     "US1"       "T001"          "side-right.jpg"    "1"      "1"
"4"     "US1"       "T001"          "back.jpg"          "1"      "1"

Right now, when I do like below to select 1 row from the first table and related rows from the second table, I get all data in every row which also repeats when I print it using php. 现在,当我像下面这样从第一张表中选择一行并从第二张表中选择相关行时,我将获得每一行中的所有数据,当我使用php打印该行时也会重复该数据。

select a.itemName, b.itemImageName from amga a left join amgb b on a.userId = b.userId where a.userId = 1;

Current Output 电流输出

"itemName"                  "itemImageName"
"Samsung Galaxy Note 5"     "front.jpg"
"Samsung Galaxy Note 5"     "side-left.jpg"
"Samsung Galaxy Note 5"     "side-right.jpg"
"Samsung Galaxy Note 5"     "back.jpg"

Desirable Output or some other variation that wont repeat the itemName and that can easily be output using php. 理想的输出或其他一些不会重复itemName且可以使用php轻松输出的变体。

"itemName"                  "itemImageName"
"Samsung Galaxy Note 5"     "front.jpg","side-left.jpg","side-right.jpg","back.jpg"

In the final results the title is output only once, whereas the image names need to be looped through. 在最终结果中,标题仅输出一次,而图像名称则需要循环显示。 Like this: 像这样:

"Samsung Galaxy Note 5"
"front.jpg","side-left.jpg","side-right.jpg","back.jpg"
select a.itemName, GROUP_CONCAT(b.itemImageName) 
from amga a 
left join amgb b 
on a.userId = b.userId 
where a.userId = 1
group by a.itemName

Use DISTINCT into GROUP_CONCAT if you dont want duplicates. 如果您不想重复,请使用DISTINCT进入GROUP_CONCAT。

You need grouping with the GROUP_CONCAT function. 您需要使用GROUP_CONCAT函数进行分组。 Please try this query: 请尝试以下查询:

select a.itemName, group_concat(b.itemImageName) 
from amga a left join amgb b on a.userId = b.userId 
where a.userId = 1 
group by a.itemName;

The group_concat operator is what you're looking for: 您正在寻找group_concat运算符:

SELECT    item_name, GROUP_CONCAT(item_image_name)
FROM      amga
LEFT JOIN amgb ON amga.userId = b.userId
WHERE     amge.userId = 1
GROUP BY  item_name

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

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