2011-11-04 68 views
1

我現在正在處理的項目需要一個參考系統(目前他們有5萬個成員)。我決定在會員表中添加refref_id字段。從同一個成員表中計算2個日期之間的新成員

的成員表的結構;

id (int auto), 
admin (enum (1,0)), 
ref (enum (1,0)), 
ref_id (int), 
country_id (int), 
city_id(int), 
town_id(int), 
totalRef (int), 
fullName (varchar), 
registrationDate (datetime) 

我想列出在兩個日期之間有新成員的查閱者數據。我想提供更多的細節,所以我也嘗試在查詢中添加國家,城市和城鎮。我嘗試了下面的查詢,但我不認爲這是一個很好的方法去考慮它需要很長時間來加載;

SELECT m.id, m.fullName, m.country_id, m.city_id, m.town_id, m.totalRef, 
(select name from country where country.id = m.country_id) as countryName, 
(select name from city where city.id = m.city_id) as cityName, 
(select name from town where town.id = m.town_id) as townName, 
(select count(id) from members where members.ref_id = m.id AND ref_id > 0 AND registrationDate BETWEEN '2011.11.04 00:00:00' AND '2011.11.04 23:59:59') as newRef 

FROM members as m 

WHERE 

m.country_id = '224' AND 
m.city_id = '4567' AND 
m.town_id = '78964' AND 
m.admin = '0' AND 
m.ref = '1' 

ORDER BY newRef DESC 
LIMIT 0, 25 

如果你能幫我解決這個問題,我會很高興。先謝謝你。

回答

1

事情是這樣的 -

SELECT 
    m.id, 
    m.fullName, 
    m.country_id, 
    m.city_id, 
    m.town_id, 
    m.totalRef, 
    cnt.name countryName, 
    ct.name cityName, 
    t.name townName, 
    m2.newRef 
FROM members as m 
    LEFT JOIN country cnt 
    ON cnt.id = m.country_id 
    LEFT JOIN city ct 
    ON ct.id = m.city_id 
    LEFT JOIN town t 
    ON t.id = m.town_id 
    LEFT JOIN (
    SELECT ref_id, COUNT(id) newRef FROM members 
     WHERE ref_id > 0 AND registrationDate BETWEEN '2011.11.04 00:00:00' AND '2011.11.04 23:59:59' 
     GROUP BY ref_id 
    ) m2 
    ON m2.ref_id = m.id 
WHERE 
    m.country_id = '224' AND 
    m.city_id = '4567' AND 
    m.town_id = '78964' AND 
    m.admin = '0' AND 
    m.ref = '1' 
ORDER BY 
    newRef DESC 
LIMIT 
    0, 25; 
+0

謝謝您的答覆。我試了一下,但有一個錯誤。 'LEFT JOIN( SELECT COUNT(ID)newRef FROM成員 WHERE REF_ID> 0 AND registrationDate '之間2011.11.04 00:00:00' AND '2011.11.04 23時59分59秒' GROUP BY REF_ID )M 2 在m2.ref_id上的m2.ref_id = m.id'上找不到列。我在'm2.ref_id = m.id'前添加了'r'成員,並將其改爲'r.id = m.ref_id'。仍然不起作用:( – Revenant

+0

是的,當然,這個ref_id字段應該被添加到SELECT列表中,我錯過了它,我修改了答案 – Devart

+0

謝謝你的作品像一個魅力和快速添加'newRef> 0'和得到了結果,我一開始並不想使用'JOINS',我不知道這些表會變得多大,所以我只是想避免使用'JOINS',但事實證明我的查詢比'JOINS',再次感謝你。 – Revenant