2012-08-23 4 views
0

UNION 명령을 사용하여 2 개의 쿼리 테이블을 추가하는 새로운 mySQL 사용자입니다. 동일한 ID를 가지고있는 경우 결과를 제외하고 노동 조합은 반복됩니다. phpMyAdmin을 통해 ID를 삭제하거나 변경하면 해당 항목이 표시됩니다. 예 : 'UNION 테이블에서 잘못된 데이터 쿼리

My day | today | 12:00 
My day | today | 12:00 

와 ID의 변화 :

OK day | other | 12:01 
My day | today | 12:00 

그리고 이것은 어떻게해야

$query = "SELECT id,title,day,time 
      FROM $db_1 
      UNION 
      SELECT id,title,day,time 
      FROM $db_2 
      WHERE month='$month' AND year='$year' ORDER BY time" ;enter code here 
$query_result = mysql_query ($query); 
while ($info = mysql_fetch_array($query_result)) 

{ 
$day = $info['day']; 
$event_id = $info['id']; 
$events[$day][] = $info['id']; 
$event_info[$event_id]['0'] = substr($info['title'], 0, 8);; 
$event_info[$event_id]['1'] = $info['time']; 
} 

답변

0

당신은

SELECT * from 
(SELECT id,title,day,time FROM $db_1 
UNION 
SELECT id,title,day,time FROM $db_2 
WHERE month='$month' AND year='$year' ORDER BY time) m 
GROUP BY id 
+1

훨씬 더 효율적인 중복 제거에 있습니다 :

의 차이에 의해 그룹을 사용하는 내 경우에는 모든 문제의 원인이 된 하위 쿼리에 filesort를 소개하는 것입니다. 많은 시간이 걸리는 어리석은 간단한 쿼리의 설명 계획을 살펴볼 때이 점을 발견했습니다. 내 대답을 편집하여 방금 생성 한 것을 보여주십시오. – Fluffeh

+0

@Fluffeh ok. 당신의 대답을 통해 갈 것입니다. 감사. – sel

+0

@Fluffeh 쿼리를 실행하고 비교해 주셔서 감사합니다. 정말로 훌륭하고 설명 된 대답. – sel

2

에 의해 그룹을 사용할 수있는 PHP 코드 트릭을 당신을 위해 :

select distinct * 
from 
(
    SELECT 
     id, 
     title, 
     day, 
     time 
    FROM 
     $db_1 
    UNION ALL 
    SELECT 
     id, 
     title, 
     day, 
     time 
    FROM 
     $db_2 
    WHERE 
     month='$month' 
     AND year='$year' 
) 
ORDER BY time 

그룹 별을 사용할 수 있지만 효율성이 떨어집니다. 나는 아래의 쿼리에 문제가 생겨서 첫 번째 쿼리가 약 10 초 만에 돌아 왔고 두 번째 쿼리는 0.5 초가 지나면 몇 가지 통계가 실행되었습니다. MySQL의 구별에

mysql> EXPLAIN select 
    -> a.mCode as cCode, 
    -> a.mName as cName 
    -> from 
    -> _user_UserStructure a 
    -> where 
    -> a.pCode in 
    -> (
    ->   select 
    ->     b.pCode 
    ->   from 
    ->     _user_userStructure b 
    ->   where 
    ->     b.mCode='RBM1' 
    ->     and b.pCode!=b.cCode 
    ->   group by 
    ->     b.pCode 
    -> ) 
    -> and a.cCode != '' 
    -> and a.pCode != a.mCode 
    -> and a.mCode!='RBM1' 
    -> group by 
    -> a.mCode, 
    -> a.mName 
    -> order by 
    -> a.mName asc; 
+----+--------------------+-------+-------+---------------+-------+---------+------+------+----------------------------------------------+ 

| id | select_type  | table | type | possible_keys | key | key_len | ref | rows | Extra          | 

+----+--------------------+-------+-------+---------------+-------+---------+------+------+----------------------------------------------+ 

| 1 | PRIMARY   | a  | ALL | cCode   | NULL | NULL | NULL | 1769 | Using where; Using temporary; Using filesort | 

| 2 | DEPENDENT SUBQUERY | b  | index | NULL   | pCode | 13  | NULL | 2 | Using where; Using filesort     | 

+----+--------------------+-------+-------+---------------+-------+---------+------+------+----------------------------------------------+ 

2 rows in set (0.00 sec) 


mysql> EXPLAIN select distinct 
    -> a.mCode as cCode, 
    -> a.mName as cName 
    -> from 
    -> _user_UserStructure a 
    -> where 
    -> a.pCode in 
    -> (
    ->   select distinct 
    ->     b.pCode 
    ->   from 
    ->     _user_userStructure b 
    ->   where 
    ->     b.mCode='RBM1' 
    ->     and b.pCode!=b.cCode 
    -> ) 
    -> and a.cCode != '' 
    -> and a.pCode != a.mCode 
    -> and a.mCode!='RBM1' 
    -> order by 
    -> a.mName asc; 
+----+--------------------+-------+----------------+---------------+-------+---------+------+------+----------------------------------------------+ 

| id | select_type  | table | type   | possible_keys | key | key_len | ref | rows | Extra          | 

+----+--------------------+-------+----------------+---------------+-------+---------+------+------+----------------------------------------------+ 

| 1 | PRIMARY   | a  | ALL   | cCode   | NULL | NULL | NULL | 1769 | Using where; Using temporary; Using filesort | 

| 2 | DEPENDENT SUBQUERY | b  | index_subquery | pCode   | pCode | 13  | func | 2 | Using where         | 

+----+--------------------+-------+----------------+---------------+-------+---------+------+------+----------------------------------------------+ 

2 rows in set (0.00 sec) 
+0

DISTINCT는 모든 열을 필요로합니다. 똑같을거야. 두 개의 테이블에서 다른 컬럼 중 일부가 다른 경우 여전히 중복 ID를 얻을 수 있습니다. – Barmar

+0

외부 쿼리에서 DISTINCT를 수행하는 경우 내부 쿼리에서 UNION ALL을 수행해야합니다. 최적화 프로그램에 중복을 두 번 제거 할 기회조차 부여 할 이유가 없습니다. –

+0

@GordonLinoff 우수 포인트. 답변을 업데이트했습니다. – Fluffeh