我有这个代码
SELECT DISTINCT idx_campus_bookinfo,c.userid as Buyer,bookname,book_explain,writedate
FROM campus_bookinfo cb
LEFT JOIN user_books ub ON idx_campus_bookinfo = id_product
LEFT JOIN customer c ON ub.id_customer = c.id_customer
where cb.idx_campus = 1 and cb.idxuser = 29 ORDER BY writedate DESC
给出
的输出我的问题是如何让买家专栏由具有相同书籍的逗号分隔。
答案 0 :(得分:3)
使用GROUP_CONCAT函数,但这意味着必须用GROUP BY替换DISTINCT:
SELECT idx_campus_bookinfo,
GROUP_CONCAT(c.userid SEPARATOR ',') as Buyer,
bookname,
book_explain,
writedate
FROM campus_bookinfo cb
LEFT JOIN user_books ub ON idx_campus_bookinfo = id_product
LEFT JOIN customer c ON ub.id_customer = c.id_customer
WHERE cb.idx_campus = 1
AND cb.idxuser = 29
GROUP BY idx_campus_bookinfo, bookname, book_explain, writedate
ORDER BY writedate DESC
后续问题,我可以对用户ID进行排序吗?
是的,你可以:
SELECT idx_campus_bookinfo,
GROUP_CONCAT(c.userid ORDER BY c.userid ASC SEPARATOR ',') as Buyer,
bookname,
book_explain,
writedate
FROM campus_bookinfo cb
LEFT JOIN user_books ub ON idx_campus_bookinfo = id_product
LEFT JOIN customer c ON ub.id_customer = c.id_customer
WHERE cb.idx_campus = 1
AND cb.idxuser = 29
GROUP BY idx_campus_bookinfo, bookname, book_explain, writedate
ORDER BY writedate DESC
答案 1 :(得分:2)
GROUP_CONCAT
会占用您的用户ID并将它们连接起来。试试这个。
SELECT idx_campus_bookinfo,
GROUP_CONCAT(c.userid) as Buyer, bookname, book_explain, writedate
FROM campus_bookinfo cb
LEFT JOIN user_books ub ON idx_campus_bookinfo = id_product
LEFT JOIN customer c ON ub.id_customer = c.id_customer
WHERE cb.idx_campus = 1 and cb.idxuser = 29
GROUP BY idx_campus_bookinfo
ORDER BY writedate DESC