我有这样的SQL查询。当我通过我的php文件执行它时,它会给出超时错误。但是当运行相同的查询thoruhg php myadmin时,它会在几秒钟内给出结果。
SELECT
cake_apartments.id,
cake_apartments.Headline,
cake_apartments.Description,
cake_apartments.photoset_id,
cake_apartments.Rental_Price,
cake_apartments.Bedrooms,
cake_apartments.Bathrooms
FROM
cake_apartments,cake_neighborhoods
WHERE
(cake_apartments.Rented = 0)
AND
(cake_apartments.status = 'Active')
ORDER BY
cake_neighborhoods.Name DESC
我知道增加时间可以解决问题。但是我不希望这个查询花费超过30秒。
答案 0 :(得分:1)
问题是你没有具体说明你们两个表之间的关系。它在phpmyadmin中快速返回,因为phpmyadmin添加了一个LIMIT子句,允许mysql服务器快速停止发送行,永远不会接近超时。
您认为查询只是检索公寓未租用且处于活动状态的行,但您真正得到的是行数*数据库中的邻域数。
像这样重写你的查询:
SELECT
cake_apartments.id,
cake_apartments.Headline,
cake_apartments.Description,
cake_apartments.photoset_id,
cake_apartments.Rental_Price,
cake_apartments.Bedrooms,
cake_apartments.Bathrooms
FROM
cake_apartments
JOIN
cake_neighborhoods
ON
cake_neighborhoods.id = cake_apartments.neighborhood_id
WHERE
(cake_apartments.Rented = 0)
AND
(cake_apartments.status = 'Active')
ORDER BY
cake_neighborhoods.Name DESC
请注意,我只是猜到两个表在ON子句中是如何相关的,所以如果我弄错了你就必须调整它。
答案 1 :(得分:1)
如果您只想要存在匹配的行,则SQL需要包含INNER JOIN。如果 cake_neighborhoods.cake_apartments_id 是 cake_neighborhoods 表中外键的名称,我建议您重写以下内容:
SELECT
cake_apartments.id,
cake_apartments.Headline,
cake_apartments.Description,
cake_apartments.photoset_id,
cake_apartments.Rental_Price,
cake_apartments.Bedrooms,
cake_apartments.Bathrooms,
cake_neighborhoods.Name
FROM
cake_apartments,cake_neighborhoods
WHERE
(cake_apartments.Rented = 0)
AND
(cake_apartments.status = 'Active')
AND
cake_neighborhoods.cake_apartments_id = cake_apartments.id
ORDER BY
cake_neighborhoods.Name DESC