两个搜索都会返回正确的结果,但当我尝试组合这两个查询时,结果都不好。

$query3 = "SELECT *
FROM airport_countries, airports
WHERE airports.iso_country=airport_countries.code &&
airport_countries.name like '%$search%'
ORDER BY pageviews DESC";

$query2 = "SELECT *
    FROM airports
    WHERE name like '%$search%' or
municipality like '%$search%'
ORDER BY pageviews DESC";

VVVVVVV型
SELECT *
FROM airport_countries, airports
WHERE airports.iso_country=airport_countries.code &&
airport_countries.name like '%$search%' or
    airports.name like '%$search%'  or
airports. municipality like '%$search%'
ORDER BY pageviews DESC

我做错什么了?

最佳答案

你的问题是一个环境是operator precedence。为了避免这种情况,请使用大括号:

SELECT *
FROM airport_countries, airports
WHERE airports.iso_country=airport_countries.code
AND (
    airport_countries.name LIKE '%$search%'
    OR airports.name LIKE '%$search%'
    OR airports. municipality LIKE '%$search%'
    )
ORDER BY pageviews DESC

我也建议使用AND而不是&&(你写的是or而不是||——看起来不太一致),但这只是我的观点,为了更好的可读性,不应该造成任何差异。

07-24 09:29