通过两个不同的列连接两个表,输入和排序

时间:2014-01-29 04:00:48

标签: mysql

我有两张桌子:

bsl_prioritas_perasat                 rek_perasat
+=========+========+=====+            +=======+==========+======+
|RUPER    |CODE    |SORT |            |CODE   |NAME      |SUB   |
+=========+========+=====+            +=======+==========+======+
|CB2RA    |R0004   |1    |            |R0004  |JASA 1    |AKA   |
|CB2RA    |R0006   |2    |            |R0006  |JASA 2    |AKB   |
|CB3RI    |R0006   |1    |            |R0008  |JASA VK   |VK    |
|CB3RI    |R0008   |2    |            |R0026  |ACCOMT    |AKOM  |
+=========+========+=====+            +=======+==========+======+

输入将是 RUPER SUB

如果bsl_prioritas_perasat上存在 RUPER ,那么它将按 SORT NAME 排序,如果 CODE < / strong>对于bsl_prioritas_perasat上的 RUPER 不存在/ NULL,它会放在最后

如果 RUPER 不存在,则会忽略 SORT ,并按 NAME

排序

示例:

1st                    2nd                    3rd
RUPER=CB2RA, SUB=AK    RUPER=CB3RI, SUB=AK    RUPER=CB5DB, SUB=AK
Result:                Result:                Result:
+==========+           +==========+           +==========+
|NAME      |           |NAME      |           |NAME      |
+==========+           +==========+           +==========+
|JASA 1    |           |JASA 2    |           |ACCOMT    |
|JASA 2    |           |ACCOMT    |           |JASA 1    |
|ACCOMT    |           |JASA 1    |           |JASA 2    |
+==========+           +==========+           +==========+

我怎样才能得到这个结果?

1 个答案:

答案 0 :(得分:0)

您应该能够使用LEFT JOIN IFNULL和默认排序值,例如:

SELECT name, sort
FROM (SELECT r.NAME, IFNULL(b.SORT, 100),
  FROM rek_perasat AS r LEFT JOIN bsl_prioritas_perasat AS b
    ON r.CODE = b.CODE AND b.RUPER = ?
  WHERE r.SUB LIKE ? + '%');

更新:添加了subselect。