douyi1197 2018-11-02 03:37
浏览 52
已采纳

SQL嵌套为一篇博文选择多个标签

I have 3 tables in a database for the blog i'm working on, posts, users and taxonomy (tags and stuff). my SQL returns and array correctly if I LIMIT 1, but I am not able to get all the tags that go with it.

Is there some sort of nesting I can do to get the tags as a an array so I can loop through them and add them to my post in one query?

The posts I've seen don't have a solution.

Needed result

{postname:"post", author:"this author",content:"stuff here", {tags: "a","b","c"}}

What ive tried:

$stmt = $this->conn->prepare("
 SELECT P.post_title,P.post_featimg, P.post_excerpt, P.post_quote,
 P.post_content, P.post_date, P.post_position, 
 U.user_firstname, U.user_lastname,
 T.taxonomy_tag        
 FROM c_blogposts P
 JOIN c_users U
 ON P.post_author and U.id
 JOIN c_taxonomy T
 ON P.post_id and T.post_id
 WHERE P.post_id = :post_id");
 $stmt->bindParam(':post_id', $id);

It will be easier to work with this fiddle as an example. Thanks

https://www.db-fiddle.com/f/u3JHfUJAZMuRWsudyLpUaS/0

  • 写回答

1条回答 默认 最新

  • douzhouqin6223 2018-11-02 03:43
    关注

    You need to use group_concat, This would do also you can customize the separator like comma or any thing you desire using separator syntax, the default is comma.

    SELECT P.content, A.author, group_concat(T.tag)
    FROM c_post P
    JOIN c_author A
    ON P.id and A.id
    JOIN c_tags T
    ON T.id and P.id
    WHERE P.id = 1
    group by P.content, A.author
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?