2013-05-06 102 views
0

我有這個數據庫:MYSQL - 加入三個表

Image : id,user_id,[..],created_at 
Visit : id,image_id,created_at 
user : id,[..] 

,我有這個疑問讓高層上傳用戶,

$current_month = date('Y-m-d', strtotime("first day of this month")) . ' 23:59:59'; 
$users = DB::query("SELECT * , 
     COUNT(p.id) as numPics 
    FROM 
     images p 
    INNER JOIN 
     users u 
    ON 
    p.user_id = u.id 
    WHERE 
    p.created_at >= \"$current_month\" 
    GROUP BY p.user_id 
    ORDER BY numPics DESC LIMIT 10"); 

我有什麼是joing訪問表,所以我可以在當前月份獲得每幅圖像的總體勝率。

+0

複製http://stackoverflow.com/questions/16406703/joing-three-tables-on-mysql – bksi 2013-05-06 20:57:00

回答

0

不知道您的訪問表的結構,我不能給出具體的細節,但你應該能夠在JOIN後添加JOIN子句訪問用戶:

SELECT *, COUNT(p.id) as numPics, COUNT(v.id) as numVisits 
FROM images p 
INNER JOIN users u ON p.user_id = u.id 
LEFT JOIN visits v ON v.image_id = p.id AND v.created_at >= "$current_month" 
WHERE p.created_at >= "$current_month" 
GROUP BY p.user_id 
ORDER BY numPics DESC LIMIT 10 
+0

它不wroks特別是在where子句! – Hamza 2013-05-06 17:09:23

+0

正如我所指出的,如果不知道訪問表的結構,我只能猜測列名和類型是什麼。您必須修改示例以適應您的情況。 – Adrian 2013-05-06 17:19:39

+0

我發佈了我的數據庫結構親愛的你可以重新閱讀這個問題。 – Hamza 2013-05-06 17:30:18

0

假設你有一個在訪問表image_id領域:

SELECT * , 
    COUNT(p.id) as numPics 
FROM 
    images p 
INNER JOIN 
    users u 
ON 
    p.user_id = u.id 

    INNER JOIN visits as v ON v.image_id = p.id 

WHERE 
p.created_at >= \"$current_month\" 
GROUP BY p.user_id 
ORDER BY numPics DESC LIMIT 10" 
+0

同樣的麻煩它不會過濾當前月份的照片它會重新顯示所有照片! – Hamza 2013-05-06 17:09:44

+0

發佈您的模式。 – timstermatic 2013-05-06 17:37:57

+0

我把它貼在這裏:http://paste.laravel.com/qDj – Hamza 2013-05-06 17:42:00