sql附加其他表的行

xj3cbfub  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(293)

我有两张table。名为“places”的主表:

还有一张标有“place\u meta”的第二张table:

在查询地点时,我想将具有相同地点id的地点\元表的行附加到地点结果。它应该看起来像:

  1. {
  2. id: 1,
  3. slug: "test",
  4. status: "active",
  5. name: "test",
  6. excerpt: "blah blah",
  7. description: "bla blah blah",
  8. test_url: "https://test.de",
  9. test2_url: "https://test2.de"
  10. }

或者类似的

  1. {
  2. id: 1,
  3. slug: "test",
  4. status: "active",
  5. name: "test",
  6. excerpt: "blah blah",
  7. description: "bla blah blah",
  8. meta: {
  9. test_url: "https://test.de",
  10. test2_url: "https://test2.de"
  11. }
  12. }

尝试了连接,但真的不知道如何得到这个愿望。

bvjveswy

bvjveswy1#

这将适用于两个预定义的元值(test\u url和test2\u url),但如果您有多个元字段,则这不是一个动态解决方案。

  1. SELECT P.*
  2. ,PM1.meta_value AS 'test_url'
  3. ,PM2.meta_value AS 'test2_url'
  4. FROM Places P
  5. LEFT JOIN place_meta PM1 ON PM1.place_id = P.id AND PM1.meta_key = 'test_url'
  6. LEFT JOIN place_meta PM2 ON PM2.place_id = P.id AND PM2.meta_key = 'test2_url'
  7. FOR JSON AUTO

相关问题