假设我有以下两个表格。我想要实现的是在A1.pagetitle
,A1.content
或A2.value
中找到匹配后按顺序返回排名结果的搜索。
但我只需要在tmplvarid
匹配特定值(在本例中为15或17)的第二个表中包含结果。
mod_site_content (A1)
+----+-----------+--------------+
| id | pagetitle | content |
+----+-----------+--------------+
| 1 | home | <p> ... </p> |
| 2 | project 1 | <p> ... </p> |
| 3 | comment 1 | <p> ... </p> |
| 4 | project 2 | <p> ... </p> |
| 5 | project 3 | <p> ... </p> |
| 6 | comment 2 | <p> ... </p> |
| etc ... |
+----+-----------+--------------+
mod_site_tmplvar_contentvalues (A2)
+----+-----------+-----------+-----------------+
| id | tmplvarid | contentid | value |
+----+-----------+-----------+-----------------+
| 1 | 2 | 1 | [{"key":"val"}] |
| 2 | 2 | 2 | [{"key":"val"}] |
| 3 | 5 | 1 | [{"key":"val"}] |
| 4 | 5 | 5 | [{"key":"val"}] |
| 5 | 15 | 4 | [{"key":"val"}] |
| 6 | 15 | 5 | [{"key":"val"}] |
| etc ... |
+----+-----------+-----------+-----------------+
我想我差不多了 - 目前我有:
SELECT DISTINCT A1.pagetitle, A1.content, A1.uri, A2.value,
CASE
WHEN A1.pagetitle LIKE ? THEN 1
WHEN A1.content LIKE ? THEN 2
WHEN A2.value LIKE ? THEN 3
END AS rank
FROM mod_site_content A1
INNER JOIN mod_site_tmplvar_contentvalues A2
ON A1.id = A2.contentid
WHERE pagetitle LIKE ?
OR content LIKE ?
OR value LIKE ?
ORDER BY rank
但这包括所有对应的contentid
- 我不能在我的生活中弄清楚如何合并一个只包含某些条件的条件。
答案 0 :(得分:2)
当你加入过滤连接列上的结果时,如此
在两个表格中回归:
SELECT DISTINCT A1.pagetitle, A1.content, A1.uri, A2.value,
CASE
WHEN A1.pagetitle LIKE ? THEN 1
WHEN A1.content LIKE ? THEN 2
WHEN A2.value LIKE ? THEN 3
END AS rank
FROM mod_site_content A1
INNER JOIN mod_site_tmplvar_contentvalues A2
ON A1.id = A2.contentid
AND A2.tmplvarid IN(15,17)
WHERE (pagetitle LIKE ?
OR content LIKE ?
OR value LIKE ?)
从mod_site_content返回行并从mod_site_tmplvar_contentvalues返回任何匹配
SELECT DISTINCT A1.pagetitle, A1.content, A1.uri, A2.value,
CASE
WHEN A1.pagetitle LIKE ? THEN 1
WHEN A1.content LIKE ? THEN 2
WHEN A2.value LIKE ? THEN 3
END AS rank
FROM mod_site_content A1
LEFT JOIN mod_site_tmplvar_contentvalues A2
ON A1.id = A2.contentid
AND A2.tmplvarid IN(15,17)
WHERE (pagetitle LIKE ?
OR content LIKE ?
OR value LIKE ?)
答案 1 :(得分:1)
最后添加条件!
SELECT DISTINCT A1.pagetitle, A1.content, A1.uri, A2.value,
CASE
WHEN A1.pagetitle LIKE ? THEN 1
WHEN A1.content LIKE ? THEN 2
WHEN A2.value LIKE ? THEN 3
END AS rank
FROM mod_site_content A1
INNER JOIN mod_site_tmplvar_contentvalues A2
ON A1.id = A2.contentid
WHERE (pagetitle LIKE ?
OR content LIKE ?
OR value LIKE ?)
AND A2.contentid in (15,17)
ORDER BY rank