2009-12-09 155 views
1

我有這樣的代碼MySQL查詢:最佳查詢

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 

這給的

Click to View output

輸出我的問題是如何讓買家列由逗號具有分隔同一本書。

回答

3

使用GROUP_CONCAT功能,但它意味着具有與基置換DISTINCT BY:

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 
+0

...看來你打我吧;) – 2009-12-09 01:54:04

+0

漂亮的一個主..這是我需要的..謝謝了一堆 – Treby 2009-12-09 01:54:59

+0

一個後續問題,我可以排序的用戶ID? – Treby 2009-12-09 02:12:25

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 
+0

那'GROUP BY'是MySQL支持的,但它與OP的查詢不一樣。 – 2009-12-09 01:54:40

+0

我喜歡你的代碼,因爲它短得多,但第一個權利,第一次服務.. 謝謝無論如何希望從這裏再次從你這裏... ... – Treby 2009-12-09 02:04:46