MySQL:判斷逗號分隔的字符串中是否包含某個字符串 && 如何在一個以逗號分隔的列表中的一個字段中連接MySQL中的多對多關系中的數據


需求:
      sql語句中,判斷以逗號分隔的字符串中是否包含某個特定字符串,類似於判斷一個數組中是否包含某一個元素,

      例如:判斷 ’a,b,c,d,e,f,g‘ 中是否包含 'a',sql語句如何實現?

解決
   1、mysql 字符串函數判斷:   FIND_IN_SET(ele, str)  

     ele 是一個特定字符,

     str 是一個以逗號分隔的字符串 或者 匹配這個參數的字段,必須以逗號分隔

select * from t_user where FIND_IN_SET('26', '1,26');

//ids: 以逗號分割的字符串
select * from t_user where FIND_IN_SET('26', ids);
   FIND_IN_SET() 函數返回該字符串所在的位置,如果不存在就返回0,

2、ORDER BY FIND_IN_SET() 可以用來排序。

   如果想讓 id 按 30 27 29 排序

select * from t_user where id in(30,27,29) order by FIND_IN_SET(id,'30,29,27');
   

 

二 原文

I have a many-to-many relationship between People and Departments since one person can be in many departments.

People          Departments
------          -----------
pID  pName      deptID   deptName
1    James      1        Engineering
2    Mary       2        Research
3    Paul       3        Marketing
                4        Communications

People_Departments
------------------
pID   deptID
1     1
1     2
2     2
2     4
3     1
3     2
3     3

What I want is this:

pName  deptName
James  Engineering, Research
Mary   Research, Communication
Paul   Engineering, Research, Marketing

If I do plain LEFT JOINs on the tables using the SQL below, I will get several rows related to one person:

SELECT people.pName,
       departments.deptName
FROM people
LEFT JOIN people_departments ON people.pID=people_departments.pID
LEFT JOIN departments ON people_departments.deptID=departments.deptID

I have tried various combinations of GROUP_CONCAT but without luck.

Any ideas to share?

解決

 SELECT people.pName,
           GROUP_CONCAT(departments.deptName SEPARATOR ', ') deptName
      FROM people
 LEFT JOIN people_departments 
        ON people.pID = people_departments.pID
INNER JOIN departments 
        ON people_departments.deptID = departments.deptID
  GROUP BY people.pID

Output:

+-------+----------------------------------+
| pName | deptName                         |
+-------+----------------------------------+
| James | Engineering, Research            |
| Mary  | Research, Communications         |
| Paul  | Engineering, Research, Marketing |
+-------+----------------------------------+
3 rows in set (0.00 sec)

 

sqlserver中的解決方法

SELECT * from cust
where
(buttonids like '%,4' or buttonids like '4,%' or buttonids like '%,4,%' or buttonids = '4') 
  or 
(buttonids like '%,5' or buttonids like '5,%' or buttonids like '%,5,%' or buttonids = '5')

 

(轉載https://blog.csdn.net/qq_42402854/article/details/88030469  &&  https://www.it1352.com/1475016.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM