如何从此查询中连接表

时间:2013-05-26 13:43:40

标签: sql join subquery

我有这个查询命令,但我想使用JOIN命令,我该怎么做。

SELECT `tkb_code`, `tko_code`, `sch_no`, `tkb_sea_name`, `tkb_mem_name`,
       `tkb_BusStop_price`,`tkh_comment`, `tks_id`, `tkr_text`, `sale_f`,
       `tkh_date` 
FROM `ticket_booking` 
WHERE tkh_updateby =60 AND tks_id =3 AND date( tkh_date ) = '2013-05-15' AND sale_f =1
AND tkb_code NOT IN (
    SELECT tkb_code
    FROM `ticket_booking` 
    WHERE tks_id =3 AND date( tkh_date ) = '2013-05-14'
    )
AND tkb_code NOT IN (
    SELECT tkb_code
    FROM `ticket_booking` 
    WHERE tks_id =6 AND date( tkh_date ) = '2013-05-15' AND tkh_updateby =60
    AND tkb_code IN (
        SELECT tkb_code
        FROM ticket_booking
        WHERE tks_id =3
        )
    )
GROUP BY tkb_code
ORDER BY tkh_date, tkb_sea_name

有人告诉我,使用JOIN时效果很好。我想替换我的查询。

1 个答案:

答案 0 :(得分:0)

尝试:

SELECT t.`tkb_code`, 
       t.`tko_code`, 
       t.`sch_no`, 
       t.`tkb_sea_name`, 
       t.`tkb_mem_name`,
       t.`tkb_BusStop_price`,
       t.`tkh_comment`, 
       t.`tks_id`, 
       t.`tkr_text`, 
       t.`sale_f`,
       t.`tkh_date` 
FROM `ticket_booking` t
LEFT JOIN `ticket_booking` ty
       ON t.tkb_code = ty.tkb_code AND 
          ty.tks_id=3 AND 
          date( ty.tkh_date ) = '2013-05-14'
LEFT JOIN `ticket_booking` t6 
          JOIN `ticket_booking` t3 
            ON t6.tkb_code = t3.tkb_code and t3.tks_id =3
       ON t.tkb_code = t6.tkb_code AND 
          t6.tks_id=6 AND 
          date( t6.tkh_date ) = '2013-05-15' AND 
          t6.tkh_updateby =60
WHERE t.tkh_updateby=60 AND 
      t.tks_id=3 AND 
      date( t.tkh_date ) = '2013-05-15' AND 
      t.sale_f=1 AND
      ty.tkb_code IS NULL AND
      t6.tkb_code IS NULL
GROUP BY t.tkb_code
ORDER BY t.tkh_date, t.tkb_sea_name