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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?