![](/img/trans.png)
[英]How to use LIKE for mysql search with JOIN and ORDER BY the count of most rows/votes in the vote table?
[英]How to join a SQL table while doing a count for the most rows?
因此,我有一個“書簽”表,我試圖為該表獲取具有最多書簽內容的用戶的“ UserID”。 該查詢返回十個最活躍用戶的UserID。 這個查詢對我來說看起來像這樣,並且可以工作:
SELECT COUNT(*) AS `Rows`, UserID FROM `bookmark`
WHERE UserID NOT IN(1, 2, 25, 38, 41, 43, 47, 125)
GROUP BY UserID ORDER BY `Rows` DESC LIMIT 10
現在,我嘗試將結果查詢加入“帳戶”表,以通過將用戶ID與帳戶表中的“ id”進行比較來獲取每個用戶ID的所有信息。
SELECT COUNT(*) AS `Rows`, UserID FROM `bookmark`
join accounts ON accounts.ID = bookmark.UserID
WHERE UserID NOT IN(1, 2, 25, 38, 41, 43, 47, 125)
GROUP BY UserID ORDER BY `Rows` DESC LIMIT 10
這不返回任何行作為accounts表,而是返回與之前相同的結果。 我需要能夠獲取帳戶表的所有行(與使用*相同)
如果有幫助,我的帳戶表中的這些行=用戶名,ID,電子郵件,而我的書簽表中的這些行= ID,用戶ID,鏈接
一種解決方案是將group by
移動到子查詢:
select *
from (
select count(*) as Rows
, UserID
from bookmark
where UserID not in (1, 2, 25, 38, 41, 43, 47, 125)
group by
UserID
) as BookmarkSubquery
join accounts
on accounts.ID = BookmarkSubquery.UserID
order by
BookmarkSubquery.Rows DESC
limit 10
另一個方法是通過以下方式將帳戶中的列添加到組中:
select count(*) as Rows
, bookmark.UserID
, accounts.Name
, accounts.BirthDate
from bookmark
join accounts
on accounts.ID = BookmarkSubquery.UserID
where bookmark.UserID not in (1, 2, 25, 38, 41, 43, 47, 125)
group by
, bookmark.UserID
, accounts.Name
, accounts.BirthDate
order by
count(*) DESC
limit 10
注意:MySQL允許您僅列出group by
bookmark.UserID
。 盡管可以,但是不建議這樣做。
這可能很難看,但是您可以將第一個查詢存儲在臨時表中,然后在帳戶和臨時表之間進行聯接。
另外,嘗試進行左聯接以查看是否有這種方式。 有時,這有助於調試查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.