SQL创建唯一的id WHERE不在IN两个表中

时间:2016-03-03 06:34:54

标签: sql

我的代码:

SELECT FLOOR(RAND() * 9999) AS random_num FROM product_list
WHERE 'random_num' NOT EXISTS 
(SELECT code_id FROM product_list) 
AND 'random_num' NOT EXISTS (SELECT p_code_id FROM item_group)
LIMIT 1 

当我使用PHP代码运行时,结果一无所获,请指教。

2 个答案:

答案 0 :(得分:0)

尝试

SELECT MAX(maxid) + 1
FROM (
SELECT MAX(code_id) maxid FROM product_list
UNION
SELECT MAX(p_code_id) maxid FROM item_group
)

答案 1 :(得分:0)

使用派生表,并调整NOT EXISTS s:

select random_num
from
(
  SELECT FLOOR(RAND() * 9999) AS random_num
  FROM product_list
) dt
WHERE NOT EXISTS (SELECT * FROM product_list where random_num = code_id) 
  AND NOT EXISTS (SELECT * FROM item_group where random_num = p_code_id)
LIMIT 1