需要根据Group_concat的结果连接两个表

时间:2016-05-04 11:40:31

标签: mysql

表1

+----+--------+-----+
| id | userId |state|
+----+--------+-----+
|  1 | 1      |AZ   |
|  2 | 1      |AK   |
|  4 | 1      |AL   |
|  5 | 1      |CO   |
|  6 | 1      |CA   |
|  7 | 2      |AZ   |
|  8 | 2      |AK   |
|  9 | 2      |AL   |
+----+--------+-----+

表2

+----+---------+--------+
| id | job  | from | to |
+----+------+------+----+
|  1 | job1 |   AZ |AK  |
|  2 | job2 |   AL |CO  |
+----+---------+--------+

我想按照他们的工作清单列出工作。从用户在mysql中允许的状态,对于上面它将返回

+------+--------+
| userId | job  | 
+--------+------+
|  1     | job1 | // As User 1 will have state AZ & AK
|  1     | job2 | // As User 1 will have state AL & CO
|  2     | job1 | // As User 2 will have state AZ & AK
+----+----------+

使用了查询:

SELECT hs.userId, j.job FROM `table2` j

JOIN (
    SELECT userId,GROUP_CONCAT(CONCAT('\'', `state`, '\'' )) as stateList FROM `table1` GROUP BY userId   
) hs ON  j.`to` IN (stateList) AND j.`from` IN (stateList) 

1 个答案:

答案 0 :(得分:1)

加入两次应该比使用group_concat更快:

SELECT u1.userId, j.job
FROM `table2` j
JOIN `table1` u1 ON u1.state = j.from
JOIN `table1` u2 ON u2.state = j.to AND u2.userId = u1.userId

我使用mysql已经有一段时间了,但是如果IN子句与MS SQL Server类似,那么它不能用逗号分隔的字符串参数,逗号分隔必须在字符串之外。您需要使用字符串比较(例如LIKE运算符)。

SELECT hs.userId, j.job FROM `table2` j
JOIN (
    SELECT userId,GROUP_CONCAT(CONCAT('\'', `state`, '\'' )) as stateList FROM `table1` GROUP BY userId   
) hs ON stateList LIKE CONCAT('%', j.`to`, '%') AND stateList LIKE CONCAT('%', j.`from`, '%')