如何进行条件查询选择

时间:2019-04-07 08:39:09

标签: php mysql sql

我有一张这样的桌子:

--------------------------------------------
|               category table             |
--------------------------------------------
id   |  name |
--------------------------------------------
1    |  book    |   --->1 digit is a category
11   |  aa      |   --->2 digit is a sub category
2    |  software|
21   |  ba      |
22   |  bb      |
23   |  bc      |

我想要这样的输出:

---------------------------------
sub_id  |name_sub |name_category
---------------------------------
11      |aa       |book
21      |ba       |software
22      |bb       |software
23      |bc       |software

选择所有子ID(2位数字),子ID名称和类别名称(从左侧开始1位数字)

3 个答案:

答案 0 :(得分:1)

从您的示例数据来看,这似乎是可以接受的快捷方式:

SELECT id sub_id, name name_sub, LEFT(name, 1) name_category
FROM category
WHERE CHAR_LENGTH(id) = 2

否则,您也可以使用JOIN:

SELECT c1.id sub_id, c1.name name_sub, c2.name name_category
FROM category c1
INNER JOIN category c2 ON c2.id = LEFT(c1.id, 1)
WHERE CHAR_LENGTH(c1.id) = 2

答案 1 :(得分:0)

您可以使用correlated subquery

select id,
       name as name_sub,
       ( select substring(name,1,1) from tab where id=t.id ) 
       as name_category
  from tab t
 where length(name)=2

Demo

答案 2 :(得分:0)

正如评论中已经提到的Wiimm,由于显而易见的原因,这对我来说似乎毫无意义,但是如果您的类别将保持2位ID,而父级始终为一位,则下面的查询将使用简单数学除法运算。

select c1.id as sub_id,c1.name as name_sub ,c2.name as name_category
from category c1
inner join category c2
on cast((c1.id / 10) as UNSIGNED) = c2.id

演示: https://www.db-fiddle.com/f/qmbYDxpDLvnzUDZ9AU4kTH/0