我有一个包含动态查询的变量。像这样:
$query = "SELECT id, subject FROM post1
UNION ALL
SELECT id, subject FROM post2
UNION ALL
SELECT id, subject FROM post3";
我也有这个问题:
SELECT code FROM mytable WHERE id = :id
现在我想用join
查询上面的动态查询。这是我的尝试:
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
*/
有效。但是大量数据需要花费大量时间。我怎样才能让它更快?
答案 0 :(得分:1)
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
只需将:id检查添加到内部querie4st以限制所选数据的数量。
答案 1 :(得分:1)
您可以使用以下查询。
SELECT t1.code, t2.subject FROM (SELECT code, col FROM mytable WHERE id = :id ) t1
LEFT JOIN ($query) t2 ON t1.col = t2.id