我通过3个查询访问我网站上的数据,首先查询获得网站上可用的完整交易列表:
$listingquery = "SELECT * FROM table WHERE city = '$city' AND approved = '1'
AND enddate > NOW() ORDER BY id DESC";
下一个查询获取可用交易提供者的计数/列表:
$providerquery = "SELECT programname, category, COUNT(name) FROM table WHERE
city = '$city' AND approved='1' AND enddate > NOW() GROUP BY provider";
和第三个查询从该城市的可用交易提供商处获取类别的计数/列表:
$categoryquery = "SELECT programname, category, COUNT(name) FROM table WHERE
city = '$city' AND approved='1' AND enddate > NOW() GROUP BY category";
有没有办法将所有这些组合成1个查询?
提前致谢!
答案 0 :(得分:0)
您可能会获得一些无损信息,但您可以尝试这样做:
SELECT * FROM table a
LEFT JOIN (
SELECT programname, category, COUNT(name)
FROM table
WHERE city = '$city' AND approved='1' AND enddate > NOW() GROUP BY provider
) b ON a.provider = b.provider
LEFT JOIN (
SELECT programname, category, COUNT(name)
FROM table
WHERE city = '$city' AND approved='1' AND enddate > NOW() GROUP BY category
) c ON a.category = b.category
WHERE a.city = '$city' AND a.approved = '1'
AND a.enddate > NOW()
ORDER BY a.id DESC;
使用一个Where子句更新(有点):
SELECT * FROM table a
LEFT JOIN (
SELECT programname, category, COUNT(name)
FROM table
WHERE enddate > NOW() GROUP BY provider
) b ON a.provider = b.provider
LEFT JOIN (
SELECT programname, category, COUNT(name)
FROM table
WHERE enddate > NOW() GROUP BY category
) c ON a.category = b.category
WHERE a.city = '$city' AND a.approved = '1'
AND a.enddate > NOW()
AND b.city = a.city AND c.city = a.city
AND b.approved = a.approved AND c.approved = a.approved
ORDER BY a.id DESC;
答案 1 :(得分:0)
我怀疑所有这些在单个查询中是可行/可行的,但无论哪种方式,您都不应该在MySQL中使用子查询,这将极大地降低性能。首选加入而不是子查询。