所以我不得不调整我使用的查询,因为表末尾的限制会导致在限制之前读取整个第一个表。这导致我的mysql服务器超时。现在我创建了一个查询,就像我在另一篇关于堆栈溢出的帖子中读到的那样,并提出了这个:
SELECT a.title
, a.lat
, a.lon
, a.a_content_id
, a.date_added
, r.countRep
, i.countInt
, content.img
, c.marker
, c.subcatvan
FROM
( SELECT title
, lat
, lon
, alert_content_id
, date_added
, cat
FROM alerts
LIMIT 10
) a
LEFT
JOIN
( SELECT COUNT(DISTINCT id) countRep
FROM reply
WHERE alert_id = alerts.alerts
) r
LEFT
JOIN
( SELECT COUNT(DISTINCT id) countInt
FROM interactions
WHERE alert_id = alerts.alerts
) i
LEFT
JOIN
( SELECT img
FROM alerts_content
WHERE alert_id = alerts.alerts
) content
LEFT
JOIN
( SELECT marker
, subcatvan
FROM categories
WHERE a.cat = id
) c;
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 45
这是我原来的查询导致超时:
SELECT
a.title, a.lat, a.lon, a.alert_content_id, a.date_added, count(DISTINCT r.id) as countRep ,count(DISTINCT i.id) AS countInt,
ac.img, c.marker, c.subcatvan
FROM `alerts` a
LEFT JOIN
`reply` r ON r.alert_id = a.alerts
LEFT JOIN
`interactions` i ON i.alert_id = a.alerts
LEFT JOIN
`alerts_content` ac ON ac.alert_id = a.alerts
LEFT JOIN
`categories` c ON a.cat = c.id
GROUP BY a.title, a.lat, a.lon, a.alert_content_id, a.date_added LIMIT 0,10
有谁知道导致错误的原因是什么? 或者知道如何更正原始查询的人?
答案 0 :(得分:1)
您需要修复子查询。他们需要使用group by
而不是相关:
SELECT a.title, a.lat, a.lon, a.a_content_id, a.date_added, r.countRep,
i.countInt, content.img, c.marker, c.subcatvan
FROM (SELECT title, lat, lon, alert_content_id, date_added, cat
FROM `alerts`
LIMIT 10
) a LEFT JOIN
(SELECT alert_id, count(DISTINCT id) as countRep
FROM `reply`
GROUP BY alert_id
) r
ON r.alert_id = a.alerts r LEFT JOIN
(SELECT alert_id, count(DISTINCT id) AS countInt
FROM `interactions`
GROUP BY alert_id
) i
ON i alert_id = a.alerts LEFT JOIN
(SELECT alert_id, img
FROM `alerts_content`
GROUP BY alert_id
) content
ON alert_id = a.alerts LEFT JOIN
`categories` c
ON a.cat = c.id;
答案 1 :(得分:-1)
尝试在where
。
c.id
代替id
答案 2 :(得分:-1)
修复了@Ravinder关于错过on子句的评论 更新了sql:
SELECT
a.alerts, a.title, a.lat, a.lon, a.alert_content_id, a.date_added, r.countRep, i.countInt,
ac.img, c.marker, c.subcatvan
FROM
(SELECT alerts, title, lat, lon, alert_content_id, date_added, cat
FROM `alerts` LIMIT 10) a
LEFT JOIN
(SELECT alert_id,count(DISTINCT id) as countRep
FROM `reply`) r
ON r.alert_id = a.alerts
LEFT JOIN
(SELECT alert_id,count(DISTINCT id) AS countInt
FROM `interactions`) i
ON i.alert_id = a.alerts
LEFT JOIN
(SELECT alert_id, img
FROM `alerts_content`) ac
ON ac.alert_id = a.alerts
LEFT JOIN
(SELECT id, marker, subcatvan
FROM `categories`) c
ON a.cat = c.id
GROUP BY a.title, a.lat, a.lon, a.alert_content_id, a.date_added