简体   繁体   中英

How to use a SELECT statement into JOIN clause?

I have a variable which is containing a dynamic query. Something like this:

$query = "SELECT id, subject FROM post1
          UNION ALL
          SELECT id, subject FROM post2
          UNION ALL
          SELECT id, subject FROM post3";

Also I have this query:

SELECT code FROM mytable WHERE id = :id

Now I want to join query above with that dynamic query. Here is my try:

SELECT t1.code t2.subject FROM mytable t1 
   LEFT JOIN ($query) t2 ON t1.col = t2.id
WHERE t1.id = :id

/*
SELECT t1.code t2.subject FROM mytable t1
   LEFT JOIN (SELECT id, subject FROM post1
               UNION ALL
              SELECT id, subject FROM post2
               UNION ALL
              SELECT id, subject FROM post3) t2 ON t1.col = t2.id
WHERE t1.id = :id
*/

It works. But it takes a lot of time for huge data. How can I make it faster?

SELECT t1.code t2.subject FROM mytable t1
   LEFT JOIN (SELECT id, subject FROM post1 
              JOIN mytable tt1 ON tt1.col = post1.id AND tt1.id=:id
               UNION ALL
              SELECT id, subject FROM post2
              JOIN mytable tt2 ON tt2.col = post2.id AND tt2.id=:id
               UNION ALL
              SELECT id, subject FROM post3
              JOIN mytable tt3 ON tt3.col = post3.id AND tt3.id=:id) t2 ON t1.col = t2.id
WHERE t1.id = :id

Just add the :id check to the internal querie4st to restrict amount of data selected.

You can use below query.

SELECT t1.code, t2.subject FROM (SELECT code, col FROM mytable WHERE id = :id ) t1 
 LEFT JOIN ($query) t2 ON t1.col = t2.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM