按IN子句中最高匹配的ORDER值

时间:2017-10-15 15:08:09

标签: mysql sql

    talb1                          tabl2
[id   -   col1]               [tid   -   col1]
[1    -    aa1]               [1     -      c]
[2    -    ba2]               [1     -      b]
[3    -    ca3]               [1     -      a]
[4    -    da4]               [1     -      d]
                              [2     -      c]
                              [2     -      a]
                              [2     -      b]
                              [3     -      b]
                              [3     -      a]
                              [4     -      a]

在以下查询中

$query = "
SELECT a.id 
FROM a.tabl1 
LEFT JOIN tabl2 b ON a.id = b.tid 
WHERE b.col1 IN ('a', 'b', 'c', 'd')
GROUP BY a.id
";

我试图获得ID内匹配的最高IN Clause s,我得到了值,但他们从未订购过,

我想按照匹配率最高的最高ID来订购

例如

ID[4] = match['a', 'b', 'c', 'd'];
ID[2] = match['a', 'b', 'c'];
ID[3] = match['a', 'b'];
ID[1] = match['a'];

所以我试过

ORDER BY COUNT(b.col1) DESC但显然我不想做任何事情,因为我希望它发生,如何订购像这样的查询呢?

注意:如果我只在a, b, c内部选择了IN Clause,我会获得有序值,但如果选中a, b, c, d(所有字母),我会得到随机值。

1 个答案:

答案 0 :(得分:1)

您需要GROUP BY才能使用ORDER BY COUNT(...)

SELECT a.id , COUNT(b.col1) AS cnt
FROM tabl1 a
LEFT JOIN tabl2 b 
  ON a.id = b.tid 
 AND b.col1 IN ('a', 'b', 'c', 'd')
GROUP BY a.id
ORDER BY cnt DESC;

<强> Rextester Demo