[英]Mysql Query Selecting Results With A Distinct Column Value
我有一張展示書籍的桌子。 但是,我希望每個唯一的電子郵件地址( strContactEmail
)只顯示一本書。 我嘗試了下面的查詢,它沒有用。 任何幫助非常感謝
$sql = "SELECT lngbookid, strTitle, strAuthor, strcoursecode, strISBN, ".
" strcontactname, DISTINCT(strContactEmail) AS strContactEmail, ".
" curPrice, ysnsalerent, dtmpostdate, memcomments, school, ".
" ASIN, BookIMG, ISBN10, ISBN13, Updated, ".
" datetime, user_ip, NoOtherBooks ".
" FROM tblbooks ".
" WHERE strcoursecode LIKE '%$search%' ".
" ORDER BY datetime DESC LIMIT 50";
嘗試GROUP BY語句:
最簡單的方法:
SELECT max(lngbookid) as lngbookid, max(strtitle) as strtitle, max(strauthor) as strauthor, max(strcoursecode) as strcoursecode, max(strisbn) as strisbn, max(strcontactname) as strcontactname, strcontactemail, max(curprice) as curprice, max(ysnsalerent) as ysnsalerent, max(dtmpostdate) as dtmpostdate, max(memcomments) as memcomments, max(school) as school, max(asin) as asin, max(bookimg) as bookimg, max(isbn10) as isbn10, max(isbn13) as isbn13, max(updated) as updated, max(datetime) as datetime, max(user_ip) as user_ip, max(nootherbooks) as nootherbooks FROM tblbooks WHERE strcoursecode LIKE '%$search%' GROUP BY strcontactemail ORDER BY datetime DESC LIMIT 50
編輯嗯,上面實際上太“假”了。 更好的方法是(提供列“lngbookid”是主鍵):
SELECT a.lngbookid,
a.strtitle,
a.strauthor,
a.strcoursecode,
a.strisbn,
a.strcontactname,
a.strcontactemail,
a.ontactemail,
a.curprice,
a.ysnsalerent,
a.dtmpostdate,
a.memcomments,
a.school,
a.asin,
a.bookimg,
a.isbn10,
a.isbn13,
a.updated,
a.datetime,
a.user_ip,
a.nootherbooks
FROM tblbooks AS a
JOIN (SELECT strcontactemail,
Max(lngbookid) AS lngbookid
FROM tblbooks
GROUP BY strcontactemail) AS b
ON ( a.strcontactemail = b.strcontactemail
AND a.lngbookid = b.lngbookid )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.