2010-07-19 6 views
0

MySQL 안에, 나는 1 : n 관계를 가진 2 개의 테이블이있다.상품의 마지막 상태를 얻으 십시요

항목 :

id |ref_num|name |... 
1 |0001 |product1|... 
2 |0002 |product2|... 

items_states :

id|product_id|state_id|date 
1 |1   |5  |2010-05-05 10:25:20 
2 |1   |9  |2010-05-08 12:38:00 
3 |1   |6  |2010-05-10 20:45:12 
... 

상태 테이블이 관련이 없습니다 만

표 항목과 같이 그 상태로 다른 테이블에 보관됩니다 제품을 가지고 state_id를 상태 이름과 연관시키는 식으로 진행됩니다.

최신 상태가 지정된 제품, 즉 행당 하나의 제품을 어떻게 얻을 수 있습니까?

답변

1

다음과 같은 시도 할 수 있습니다 감사합니다

SELECT i.ref_num, i.name, s.latest_date 
FROM items i 
JOIN (
      SELECT product_id, MAX(date) as latest_date 
      FROM  items_states 
      GROUP BY product_id 
     ) s ON (s.product_id = i.id); 

단순히 쿼리에 WHERE i.id = ?을 추가 한 항목을 반환합니다.

테스트 케이스 :

CREATE TABLE items (id int, ref_num varchar(10), name varchar(10)); 
CREATE TABLE items_states (id int, product_id int, state_id int, date datetime); 

INSERT INTO items VALUES (1, '0001', 'product1'); 
INSERT INTO items VALUES (2, '0002', 'product2'); 

INSERT INTO items_states VALUES (1, 1, 5, '2010-05-05 10:25:20'); 
INSERT INTO items_states VALUES (2, 1, 9, '2010-05-08 12:38:00'); 
INSERT INTO items_states VALUES (3, 1, 6, '2010-05-10 20:45:12'); 

결과 : second.id이고

+---------+----------+---------------------+ 
| ref_num | name  | latest_date   | 
+---------+----------+---------------------+ 
| 0001 | product1 | 2010-05-10 20:45:12 | 
+---------+----------+---------------------+ 
1 row in set (0.02 sec) 
0

어느 LEFT가 second.date> first.date을 요구 자체에 items_states 테이블을 가입하고는 넣어 그 안에 NULL 절 :

SELECT a.* 
FROM item_states a 
LEFT JOIN item_states b 
ON a.product_id = b.product_id 
AND b.product_id > a.product_id 
WHERE b.id IS NULL AND a.state_id = <desired state> 

또는 Mark Byers 예제를 참조하십시오.

관련 문제