2013-04-25 55 views
0

我知道如何獲得最大ID。這很容易。但我有一個情況的MaxID可以有1例的值的行..我有如下表:MySQL獲取結果的最大ID,除非列中的值等於1

CREATE TEMPORARY TABLE people (
    id INT NOT NULL 
    ,NAME VARCHAR(50) NOT NULL 
); 

INSERT INTO people (id, NAME) VALUES (1, 'tony'); 
INSERT INTO people (id, NAME) VALUES (2, 'dave'); 
INSERT INTO people (id, NAME) VALUES (3, 'dan'); 

CREATE TEMPORARY TABLE orders (
    id INT NOT NULL 
    ,peopleid INT NOT NULL 
    ,VALUE INT 
); 

INSERT INTO orders (id, peopleid, VALUE) VALUES (1, 1, NULL); 
INSERT INTO orders (id, peopleid, VALUE) VALUES (2, 1, 1); 
INSERT INTO orders (id, peopleid, VALUE) VALUES (3, 1, NULL); 
INSERT INTO orders (id, peopleid, VALUE) VALUES (4, 2, NULL); 
INSERT INTO orders (id, peopleid, VALUE) VALUES (5, 2, NULL); 
INSERT INTO orders (id, peopleid, VALUE) VALUES (6, 2, NULL); 
INSERT INTO orders (id, peopleid, VALUE) VALUES (7, 2, NULL); 
INSERT INTO orders (id, peopleid, VALUE) VALUES (8, 1, NULL); 
INSERT INTO orders (id, peopleid, VALUE) VALUES (9, 2, NULL); 

,當我運行查詢:

SELECT * FROM people AS p 
    LEFT JOIN orders AS o ON o.peopleid = p.id 

我得到的結果:

id name id peopleid value 
1 tony 1 1   null 
1 tony 2 1   1 
1 tony 3 1   null 
1 tony 8 1   null 
2 dave 4 2   null 
2 dave 5 2   null 
2 dave 6 2   null 
2 dave 7 2   null 
2 dave 9 2   null 
3 dan null null  null 

我需要的結果

id name id peopleid value 
1 tony 2 1   1 
2 dave 9 2   null 
3 dan null null  null 

回答

2
SELECT id FROM tablename 
ORDER BY value=1 DESC, id DESC 
LIMIT 1; 


SELECT persons.personid,persons.name,othertable.id 
FROM persons 
LEFT JOIN othertable 
    ON othertable.personid = persons.personid 
LEFT JOIN othertable check 
    ON check.personid = persons.personid 
    ON check.id > othertable.id 
    AND (othertable.value!=1 OR check.value=1) 
WHERE check.personid IS NULL; 

決賽:

SELECT people.id,people.NAME,orders.id,orders.VALUE 
FROM people 
LEFT JOIN orders 
    ON orders.peopleid = people.id 
LEFT JOIN orders checkbigger 
    ON checkbigger.peopleid = people.id 
    AND (
    (
     checkbigger.id > orders.id 
     AND orders.value <=> checkbigger.value 
    ) 
    OR 
    (
     orders.value IS NULL AND checkbigger.value IS NOT NULL 
    ) 
) 
WHERE checkbigger.id IS NULL; 
+0

我使用此表作爲加入,所以我不能做限制1. – 2013-04-25 18:46:52

+0

你再質疑添加您實際的查詢,我們將看看我們是否可以得到它在加入或是否需要子查詢。 – Wrikken 2013-04-25 18:47:47

+0

好吧..我更新了問題與2表..我會在查詢..但它會是錯誤的..顯然爲什麼我要添加問題..哈哈 – 2013-04-25 18:53:15

1

這將不使用LIMIT工作。如果沒有value = 1行,則第一個MAX將爲空,因此COALESCE會返回第二個MAX。如果有value = 1行,則第一個MAX將爲非null,因此將返回。

SELECT 
    COALESCE(
    MAX(CASE WHEN value = 1 THEN id END), 
    MAX(CASE WHEN value IS NULL THEN id END)) 
FROM a 
相關問題