我在单独的查询中查询两个表。这样做可以在不到一秒的时间内得到正确的结果,但是,如果我尝试合并它们,我甚至需要杀死查询(很多记录)需要很长时间。我想知道我做错了什么。
所需输出
+--------+-----------+-----------+-----------+
| name | computers | printers | tvs |
+--------+-----------+-----------+-----------+
| Peter | 12 | 1 | 5 |
| Josh | 20 | 4 | |
| Bob | 15 | 4 | 9 |
+--------+-----------+-----------+-----------+
查询1
SELECT
names.name,
SUM(IF(pcs.electronic = 'computers', 1,0)) AS computers,
SUM(IF(pcs.electronic = 'printers', 1,0)) AS printers
FROM
electronics.pcs LEFT JOIN electronics.orders
ON pcs.id = orders.id
LEFT JOIN electronics.buying
ON orders.id = buying.id
LEFT JOIN dbnames.names names
ON names.clientid = pcs.clientid
WHERE
pcs.clientid IS NOT NULL AND
pcs.belongs IN (10)
GROUP BY pcs.clientid
表1 - 查询1
+--------+-----------+-----------+
| name | computers | printers |
+--------+-----------+-----------+
| Peter | 12 | 1 |
| Josh | 20 | 4 |
| Bob | 15 | 4 |
+--------+-----------+-----------+
查询2
SELECT
names.name,
SUM(IF(tvs.electronic = 'tvs', 1,0)) AS tvs
FROM
electronics.tvs LEFT JOIN dbnames.names names
ON names.clientid = tvs.clientid
WHERE
tvs.belongs IN (10)
GROUP BY tvs.clientid
表2 - 查询2
+--------+-----------+
| name | tvs |
+--------+-----------+
| Peter | 5 |
| Bob | 9 |
+--------+-----------+
答案 0 :(得分:0)
为什么不做一个简单的 UNION
?
SELECT
names.name,
SUM(IF(pcs.electronic = 'computers', 1,0)) AS computers,
SUM(IF(pcs.electronic = 'printers', 1,0)) AS printers
FROM
electronics.pcs LEFT JOIN electronics.orders
ON pcs.id = orders.id
LEFT JOIN electronics.buying
ON orders.id = buying.id
LEFT JOIN dbnames.names names
ON names.clientid = pcs.clientid
WHERE
pcs.clientid IS NOT NULL AND
pcs.belongs IN (10)
GROUP BY pcs.clientid
UNION ALL
SELECT
names.name,
SUM(IF(tvs.electronic = 'tvs', 1,0)) AS tvs
FROM
electronics.tvs LEFT JOIN dbnames.names names
ON names.clientid = tvs.clientid
WHERE
tvs.belongs IN (10)
GROUP BY tvs.clientid
只是一个想法...
答案 1 :(得分:0)
完全连接可以很好地工作,但由于MySQL不支持完全连接..你可以在两者之间使用UNION ALL并从相应的列中获取MAX。
SELECT clientid, name,
MAX(computers) computers,
MAX(printers) printers,
MAX(tvs) tvs
FROM
(
SELECT
pcs.clientid,
names.name,
SUM(IF(pcs.electronic = 'computers', 1,0)) AS computers,
SUM(IF(pcs.electronic = 'printers', 1,0)) AS printers,
NULL
FROM
electronics.pcs LEFT JOIN electronics.orders
ON pcs.id = orders.id
LEFT JOIN electronics.buying
ON orders.id = buying.id
LEFT JOIN dbnames.names names
ON names.clientid = pcs.clientid
WHERE
pcs.clientid IS NOT NULL AND
pcs.belongs IN (10)
GROUP BY pcs.clientid, names.name
UNION ALL
SELECT
tvs.clientid,
names.name,
NULL, NULL,
SUM(IF(tvs.electronic = 'tvs', 1,0)) AS tvs
FROM
electronics.tvs LEFT JOIN dbnames.names names
ON names.clientid = tvs.clientid
WHERE
tvs.belongs IN (10)
GROUP BY tvs.clientid, names.name
) Q2
GROUP BY clientid, name
答案 2 :(得分:0)
select *
from
(
... first query
) as query1
left join
(
... second query
) as query2
on query1.name=query2.name;