3

整个查询:

SELECT NULL, 
ELT( MOD( A.contact_id, (SELECT count(*) FROM  `ak_contact` WHERE  `contact_type_id` = 12) )+1, (SELECT  CONCAT( "'",GROUP_CONCAT(CAST(contact_id  AS CHAR(7)) SEPARATOR "','"),"'"  )  FROM  `ak_contact` WHERE  `contact_type_id` = 12) ) as operator_id,
B.account_id, A.contact_id, A.email
FROM ak_contact A
JOIN ak_accounts B USING (contact_id)
GROUP BY A.email, A.contact_id, B.account_id
ORDER BY A.contact_id DESC

子查询应为每一行一一选择 ID 号 10493、10495、11262、11800、12362、13405 之一:

ELT( MOD( A.contact_id, (SELECT count(*) FROM  `ak_contact` WHERE  `contact_type_id` = 12) )+1, (SELECT  CONCAT( "'",GROUP_CONCAT(CAST(contact_id  AS CHAR(7)) SEPARATOR "','"),"'"  )
#result: ELT(MOD(3333, 5)+1, '10493','10495','11262','11800','12362','13405')   

问题是我不能强迫 ELT(A.contact_id, subquery) 与子查询一起工作。或者我怎么能做这样的事情:

ELT(MOD(3333, 5)+1, '10493','10495','11262','11800','12362','13405')

在主查询内部

4

2 回答 2

1

您可以使用 FIND_IN_SET 和子查询,该子查询使用 GROUP_CONCAT 将所有值作为逗号分隔的字符串 '10493,10495,11262,...' 提供。

(但请注意,GROUP_CONCAT 可以返回的字符串大小受服务器配置的限制。)

于 2013-06-18T12:54:49.027 回答
0

表格 MySQL 8 您可以使用:

WITH
cte1 AS (
   SELECT
      (MOD( A.contact_id, (SELECT count(*) FROM  ak_contact WHERE  contact_type_id = 12) )+1)mx,
      B.account_id,
      A.contact_id,
      A.email
   FROM ak_contact A
      INNER JOIN ak_accounts B USING (contact_id)
GROUP BY A.email, A.contact_id, B.account_id
), 
cte2 AS (
   SELECT
      (ROW_NUMBER() OVER ())mx,
      CAST(contact_id  AS CHAR(7))cid
   FROM ak_contact
   WHERE contact_type_id = 12
)
SELECT cte1.*, cte2.*
FROM cte1
LEFT JOIN cte2 ON cte1.mx = cte2.mx
ORDER BY cte1.contact_id DESC;
于 2019-10-26T13:40:34.090 回答