问题
My table looks like as follows; (I populated it from excel)
I want to extract some data from another table so I use sql joins. Since my column contains comma separated values, i try to use join with Or but no success. Is this right way to do joins? I look for quick solution for this comma separated columns.
eg:
SELECT * FROM test.types as a
inner join test.`matric as ma on (a.category= SUBSTRING_INDEX(ma.`Function Code AA`,',',1)
or a.category= SUBSTRING_INDEX(ma.`Function Code AA`,',',2)
or a.category= SUBSTRING_INDEX(ma.`Function Code AA`,',',3)
or a.category= SUBSTRING_INDEX(ma.`Function Code AA`,',',4)
or a.category= SUBSTRING_INDEX(ma.`Function Code AA`,',',5)
or a.category= SUBSTRING_INDEX(ma.`Function Code AA`,',',6))
and a.type = ma.`function Code NN` and ma.`Priority` = "T1"
回答1:
You have a horrible data model. You probably cannot speed up the query very much. But you can at least simplify the code.
SELECT *
FROM test.types t JOIN
test.matric ma
ON FIND_IN_SET(t.category, REPLACE(ma.`Function Code AA`, ', ', ',')) > 0 OR
t.type = ma.`function Code NN`
WHERE ma.`Priority` = 'T1';
However, you should fix your data model!!!. Here are some issues:
- Databases have very poor string processing capabilities.
- Values should be stored using the correct type.
- Foreign keys should be declared properly.
- Such a structure prevents the database from using indexes, partitions, and the best optimization methods.
SQL has a great way to store lists. It is not called a string. It is called a table.
来源:https://stackoverflow.com/questions/58908549/can-we-do-a-sql-join-with-or-key-word