tags:

views:

33

answers:

2

hi there

i have two queries, querying the same table, but based on different parameters,

i then need to mush these two result sets together based on certian parameters

//get initial text
Q1
SELECT 
campaign_id AS campaign_id, 
from_number AS mobile,
received_msg AS join_txt,
date_received AS join_txt_date
 FROM received_txts WHERE action_id = 4 AND msg_link_id = id;

//get final text
Q2
SELECT 
campaign_id AS campaign_id, 
from_number AS mobile,
received_msg AS final_txt,
date_received AS final_txt_date
 FROM received_txts WHERE action_id = 4 AND msg_complete_id = id;

/join these two queries on
Q2.msg_link_id = Q1.id AND Q2.campaign_id = Q1.campaign_id AND Q2.from_number = Q1.from_number
A: 

use a virtual table:

SELECT *
FROM table AS t1
JOIN ( select .. ) AS t2
ON ( t1.foo = t2.foo )
Evan Carroll
I tried doing SELECT t1.campaign_id AS campaign_id, t1.from_number AS mobile, t1.received_msg AS join_txt, t1.date_received AS join_txt_date, t2.final_txt AS final_txt, t2.final_txt_date AS final_txt_date FROM received_txts AS t1 (part 2 below)
Hailwood
JOIN ( SELECT id AS id, msg_complete_id AS msg_complete_id, msg_link_id AS msg_link_id, campaign_id AS campaign_id, from_number AS mobile, received_txt AS final_txt, date_received AS final_txt_date WHERE msg_complete_id = id ) AS t2ON ( t1.msg_link_id = t1.id AND t2.msg_link_id = t1.id AND t2.campaign_id = t1.campaign_id AND t2.from_number = t1.from_number AND t2. )but i get: error in your SQL syntax; near 'where msg_complete_id = id ) AS t2ON ( t1.msg_link_id = t1.id and t2.msg_li'
Hailwood
+2  A: 
SELECT 
  Q1.campaign_id AS campaign_id, 
  Q1.from_number AS mobile,
  Q1.received_msg AS join_txt,
  Q1.date_received AS join_txt_date,
  Q2.received_msg AS final_txt,
  Q2.date_received AS final_txt_date
FROM received_txts Q1 JOIN received_txts Q2
  ON Q2.msg_link_id = Q1.id
    AND Q2.campaign_id = Q1.campaign_id
    AND Q2.from_number = Q1.from_number
WHERE Q1.action_id = 4
  AND Q2.action_id = 4
  AND Q1.msg_link_id = Q2.id
  AND Q2.msg_complete_id = Q2.id
Amadan
I would have used a sub query on action_id=4, but other than that, I'd go with this. Any reason you didn't?
Roger Willcocks
Subquery? I don't know, why? Would it be faster?
Amadan