MySQL(简化表格)
TABLE_1
+----+-------+
| id | title |
+----+-------+
| 1 | test |
+----+-------+
| 2 | test |
+----+-------+
| 3 | test |
+----+-------+
TABLE_2
+----+
| id |
+----+
| 1 |
+----+
TABLE_3
+----+
| id |
+----+
| 1 |
+----+
| 3 |
+----+
PHP
$a = mysql_query("SELECT t1.id FROM table_1 AS t1 WHERE MATCH(t1.title) AGAINST ('test' IN BOOLEAN MODE)");
我现在想做的是:
a)如果id
或table_2
中包含table_3
,则其排名应高于table_1
b)如果id
和table_2
中包含table_3
,则排名应该更高
所以,输出应该是:
1, 3, 2
答案 0 :(得分:1)
select table_1.id,
(case
when max(table_2.id) is not null AND max(table_3.id) is not null then 0
when max(table_2.id) is not null OR max(table_3.id) is not null then 1
else 2
end) rank
from table_1 left outer join table_2 on
table_1.id = table_2.id left outer join table_3 on
table_1.id = table_3.id
group by table_1.id
order by rank
答案 1 :(得分:1)
SELECT a.id
FROM table_1 a
LEFT JOIN table_2 b ON b.id = a.id
LEFT JOIN table_3 c ON c.id = a.id
ORDER BY
b.id IS NOT NULL AND c.id IS NOT NULL DESC,
b.id IS NOT NULL OR c.id IS NOT NULL DESC
当多个条目具有相同的优先级时,您可以对后续的排序进行广告