我有两个表Board1和Board2具有相同的结构。它们都具有id
的主索引列。我有一个名为Table1的第三个表,它有一个非索引列board_id
,其中多次出现相同的board_id
。 board_id
始终对应Board1中的id
。 Board2当前是空的,我想从Board1添加行,但只在Table1中至少六次出现相同board_id
的行。 Table1将会定期更改,因此我将来需要进行查询,但不会使已经在Board2中的id
行加倍。
所以回顾一下:
有三个表:Board1,Board2和Table1。我想将行从Board1复制到Board2,但仅限于Board1中的id
在表1中出现(至少)六次,作为`board_id'。
我很感激任何帮助!
编辑:我非常抱歉,但我意识到我在我的问题上犯了一个大错。我重写了它以反映我实际需要的东西。我很抱歉。答案 0 :(得分:0)
你可以这样做
INSERT INTO Table2
SELECT
id,
board_id
FROM (SELECT
b.id,
b.board_id,
bl.Count
FROM board as b
LEFT JOIN (SELECT
board_id,
COUNT(board_id) as `Count`
FROM board
GROUP BY board_id) as bl
on bl.board_id = b.board_id
group by b.id
having bl.Count >= 6) as L
如果您需要更多列,可以在内部和外部查询中选择它们。
答案 1 :(得分:0)
尝试以下内容:
SELECT * FROM Table1
您可能需要测试/验证
INSERT INTO Board2 (Your Column Names)
SELECT (Your Column Names)
FROM Board1
WHERE id (IN (SELECT board_id
FROM Table1
GROUP BY (board_id)
HAVING (COUNT(*) >= 6))
AND board_id NOT IN(SELECT DISTINCT board_id FROM Board2)
答案 2 :(得分:0)
以下是您要求的内容fiddle
INSERT Table2
SELECT
*
FROM
Table1
JOIN
(
SELECT
Board_Id,
count(*) cnt
FROM
Table1
GROUP BY
Board_Id
) BoardIds
ON BoardIds.Board_Id = Table1.Board_Id
WHERE
BoardIds.cnt > 5
AND
NOT EXISTS (SELECT id FROM Table2 WHERE Table2.id = Table1.id)