2011-11-06 72 views
1

我有一個表Markidname場和第二表mark_id和兩個額外的列我感興趣的是獲得不同列中。我想從Mark表+優先適用於所有記錄標記和created_at。可能有幾個值,但我不太在乎它們,我只需要一個(首先,不管)。SQL JOIN從第二臺

我試過這個查詢,它給了我太多的記錄,5而不是3我期望。

SELECT 
    marks.*, 
    markings.created_at, 
    markings.created_at AS updated_at, 
    markings.priority 
FROM `marks` 
JOIN markings 
    ON marks.id = markings.tag_id 
WHERE (created_at > '2011-11-06 12:05:01') 
    AND (priority = 1) 
ORDER BY created_at; 

回答

3
SELECT 
    marks.*, 
    MIN(markings.created_at) as created_at, 
    MIN(markings.created_at) AS updated_at, 
    markings.priority 
FROM `marks` 
JOIN markings 
    ON marks.id = markings.tag_id 
WHERE (created_at > '2011-11-06 12:05:01') 
    AND (priority = 1) 
GROUP BY marks.col1, marks.col2, ... marks.coln, markings.priority 
ORDER BY created_at; 

其中marks.col1, marks.col2, ... marks.coln將你的情況marks.id, marks.name如果你沒有更多的列你不告訴我們。

1

此查詢組通過標誌和編號的結果,應該是你想要的東西:

SELECT 
    marks.id, 
    MAX(markings.created_at), 
    MAX(markings.created_at) AS updated_at, 
    markings.priority 
FROM `marks` 
JOIN markings 
    ON marks.id = markings.tag_id 
WHERE (created_at > '2011-11-06 12:05:01') 
    AND (priority = 1) 
GROUP BY marks.id,markings.priority 
ORDER BY updated_at; 
+0

列「marks.name」在選擇列表中無效,因爲它不是在聚合函數或包含GROUP BY子句。 –

+0

「marks.created_at」列在ORDER BY子句中無效,因爲它不包含在聚合函數或GROUP BY子句中。 –