如何按同一表上存在的行进行筛选和排序?

时间:2019-05-23 06:54:40

标签: mysql sql

我有一个简单的表,其中有2列“ id”和“ ink_number”,我想创建另一个名为“ nk_exists”的列,该列的值为1或0,具体取决于是否有像这样的行,但是开头是“ NK”。并可以按“ nk_exits”排序。

例如,如果有两行“ 123”和“ NK123”,那么对于行“ 123”,nk_exists为true,因为存在以NK开头的行123。

这是我的原始表“ inkasso”

+-------+--------------+
| id  1 |  ink_number  |
+-------+--------------+
|     1 | 538032S      |
|     2 | NK538032S    |
|     3 | 114702A      |
|     4 | 159631D      |
|     5 | NK9761926001 |
|     6 | 9761926001   |
|     7 | 29-00002411L |
|     8 | 42032502V    |
|     9 | NK42032502V  |
|    10 | 454339KDB    |
+-------+--------------+

我希望最终结果看起来像这样

+-------+--------------+-----------+
| id  1 |  ink_number  | nk_exists |
+-------+--------------+-----------+
|     1 | 538032S      |         1 |
|     2 | NK538032S    |         0 |
|     3 | 114702A      |         0 |
|     4 | 159631D      |         0 |
|     5 | NK9761926001 |         0 |
|     6 | 9761926001   |         1 |
|     7 | 29-00002411L |         0 |
|     8 | 42032502V    |         1 |
|     9 | NK42032502V  |         0 |
|    10 | 454339KDB    |         0 |
+-------+--------------+-----------+

我的查询出现了Synax错误

  

1064-您的SQL语法有错误;检查与您的MariaDB服务器版本相对应的手册以获取正确的语法

select
    inkasso.id,
    inkasso.ink_number,
    jointable.nk_exists
from inkasso
left join (
    select
        case
            when exists 1
            when not exists 0
        end as nk_exists
    from inkasso
    where exists(
        select
            1
        from inkasso ink
        where left(ink_number, 2) = 'NK' and inkasso.id = ink.id
    ) as subjoin on 
) as jointable on inkasso
WHERE jointable.nk_exists = 1
ORDER BY jointable.nk_exists

2 个答案:

答案 0 :(得分:2)

SELECT *,
  CONCAT('NK', ink_number) IN (SELECT ink_number FROM inkasso) AS nk_exists
FROM inkasso;

Fiddle

答案 1 :(得分:1)

如果sou要添加nk_exists,则可以尝试执行以下操作:

SELECT          ink.id,
                ink.ink_number,
                CASE
                  WHEN nk_ink.id IS NULL THEN 0
                  ELSE                        1
                END AS nk_esists
FROM            inkasso ink
LEFT OUTER JOIN inkasso nk_ink
             ON nk_ink.ink_number = 'NK' + ink.ink_number

如果只想对该列进行过滤,则可以尝试以下操作:

SELECT ink.id,
       ink.ink_number,
FROM   inkasso ink
WHERE  EXISTS (SELECT nk_ink.id
               FROM   inkasso nk_ink
               WHERE  nk_ink.ink_number = 'NK' + ink.ink_number)