2012-10-25 72 views
0

算我想從一個表中獲取數據,並計算從其他表中的所有結果,根據第一表數據,這裏是我的嘗試:MySQL查詢以及其他表

SELECT 
    cars.*, (
     SELECT 
      COUNT(*) 
     FROM 
      uploads 
     WHERE 
      uploads.cid = cars.customer 
    ) AS `count`, 
FROM 
    `cars` 
WHERE 
    customer = 11; 

我不真的有一個想法,爲什麼它不工作,因爲我不是一個普通的MySQL用戶/編碼器...

任何人都可以指引我在這個正確的方向嗎?

+0

是否拋出任何異常? –

回答

1
SELECT 
    c.*, COUNT(u.cid) AS count 
FROM 
    cars c 
LEFT JOIN 
    uploads u 
ON 
    u.cid=c.customer 
WHERE 
    u.customer = 11; 
GROUP BY c.cid 
1

使用LEFT JOIN

SELECT a.customer, COUNT(b.cid) totalCount 
FROM cars a 
     LEFT JOIN uploads b 
      ON a.customer = b.cid 
WHERE a.customer = 11 
GROUP BY a.customer 

LEFT JOIN使用COUNT(*)都會有記錄加入這兩個表試試它有1

+0

這隻從'cars'表中選擇一條記錄。 :/ – Scott

0
SELECT cars.*,COUNT(uploads.*) as uplloaded 
from cars 
left outer join uploads on uploads.cid = cars.customer 
where cars.customer = 11 
group by uploads.cid; 
0

最小計數試試這個:

SELECT customer, COUNT(cid) totalCount 
FROM cars 
     INNER JOIN uploads 
      ON (customer = cid) 
WHERE customer = 11 
GROUP BY customer