【问题标题】:JOIN two tables into array by key通过键将两个表连接到数组中
【发布时间】:2014-01-02 22:29:03
【问题描述】:

我有两个表想要加入到数组中,其中包含 table2 的数组:

table1
id   value
----------
1    red
2    blue

table2
id   url
-----------
1    image1
1    image2
1    image3
2    image1
2    image2
2    image3

MySQL 查询是:

SELECT HIGH_PRIORITY * FROM table1
                  LEFT JOIN table2 ON table1.id = table2.id
                      WHERE table1.id = 1

我希望得到如下结果:

Array
(
  [value] => red
    (
    [url] => Array
     (
      [0] => image1
      [1] => image2
      [2] => image3
     )
    )

)

但是根据table2的条目数量总是table1的倍数

Array
(
  [0] => Array
  (
    [value] => red
    [url] => image1
  )
  [1] => Array
  (
    [value] => red
    [url] => image2
  )
  [2] => Array
  (
    [value] => red
    [url] => image3
  )
)

我应该在查询中更改什么以获得所需的数组?

【问题讨论】:

  • 你可以做一个 GROUP_CONCAT 并且你会有你的第一个数组,但是键 0 ='image1,image2,image3'
  • 你为什么使用 MyISAM 而不是 InnoDB?

标签: mysql arrays select join grouping


【解决方案1】:

看起来运算符的关联性与您的预期相反。你有没有试过这个:

SELECT HIGH_PRIORITY * FROM (
    SELECT table1.id, table2.url
    FROM table1
    LEFT JOIN table2 ON table1.id = table2.id
    WHERE table1.id = 1
) data

【讨论】:

    猜你喜欢
    • 2011-01-28
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 2019-08-03
    • 2014-07-23
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多