1

这个查询在三个查找表lslold的帮助下从一个主表m、三个辅助表sod中获得了我想要的结果,但是它为每个字段查询每个表一次。

SELECT m.id, 
(SELECT GROUP_CONCAT(s.field1 SEPARATOR ', ')
    FROM s, ls
    WHERE ls.mid=m.id AND ls.sid=s.id) 
    AS s_field,
(SELECT GROUP_CONCAT(o.field1 SEPARATOR ', ')
    FROM o, lo
    WHERE lo.mid=m.id AND lo.oid=o.id) 
    AS o_field1,
(SELECT GROUP_CONCAT(o.field2 SEPARATOR ', ')
    FROM o, lo
    WHERE lo.mid=m.id AND lo.oid=o.id) 
    AS o_field2,
(SELECT GROUP_CONCAT(o.field3 SEPARATOR ', ')
    FROM o, lo
    WHERE lo.mid=m.id AND lo.oid=o.id) 
    AS o_field3,
(SELECT GROUP_CONCAT(o.field4 SEPARATOR ', ')
    FROM o, lo
    WHERE lo.mid=m.id AND lo.oid=o.id) 
    AS o_field4,
(SELECT GROUP_CONCAT(d.field1 SEPARATOR ', ')
    FROM d, ld
    WHERE ld.mid=m.id AND ld.did=d.id) 
    AS d_field1,
(SELECT GROUP_CONCAT(d.field2 SEPARATOR ', ')
    FROM d, ld
    WHERE ld.mid=m.id AND ld.did=d.id) 
    AS d_field2
FROM m
WHERE m.id=22 GROUP BY m.id

如何重写它以获得相同的结果,但每个表只有一个子查询。

4

1 回答 1

1

您可以使用以下内容:

SELECT m.id, 
    GROUP_CONCAT(sls.field1 SEPARATOR ', ') AS s_field,
    GROUP_CONCAT(olo.field1 SEPARATOR ', ') AS o_field1,
    GROUP_CONCAT(olo.field2 SEPARATOR ', ') AS o_field2,
    GROUP_CONCAT(olo.field3 SEPARATOR ', ') AS o_field3,
    GROUP_CONCAT(olo.field4 SEPARATOR ', ') AS o_field4,
    GROUP_CONCAT(dld.field1 SEPARATOR ', ') AS d_field1,
    GROUP_CONCAT(dld.field2 SEPARATOR ', ') AS d_field2,
FROM m
(
    SELECT ls.mid, s.field1
    FROM s
    INNER JOIN ls
        on s.id = ls.sid
) sls
    on m.id = sls.mid
INNER JOIN
(
    SELECT lo.mid, o.field1, o.field2, o.field3, o.field4
    FROM o
    INNER JOIN lo
        on o.id = lo.oid
) olo
    on m.id = olo.mid
INNER JOIN
(
    SELECT ld.mid, d.field1, d.field2
    FROM d
    INNER JOIN ld
        on d.id = ld.did
) dld
    on m.id = dld.mid
WHERE m.id=22 
GROUP BY m.id
于 2012-08-23T21:24:31.433 回答