[英]MySql query to insert row with multiple conditions
我需要為所有等於特定條件的 post_id 添加一個新行。 所以有一個包含post_id
、 meta_key
和meta_value
的表
ID | post_id | 元密鑰 | 元值 |
---|---|---|---|
1個 | 100 | 頁面類型 | 城市 |
2個 | 100 | 橫幅 | “橫幅” |
3個 | 101 | 頁面類型 | 城市 |
4個 | 102 | 頁面類型 | 城市 |
5個 | 102 | 橫幅 | “新旗幟 |
6個 | 111 | 頁面類型 | 非城市 |
7 | 111 | 橫幅 | “非城市旗幟” |
我需要為具有meta_key = "page-type"
和meta_value = "city"
而meta_key = "banner"
不存在的 post_id 添加。 在這個例子中,我應該有一個新行
ID | post_id | 元密鑰 | 元值 |
---|---|---|---|
8個 | 101 | 橫幅 | “我的新旗幟” |
當然該表包含大約 200K 這樣的行:)有什么建議嗎?
INSERT INTO
post (
post_id,
meta_key,
meta_value
)
SELECT
post_id,
'banner',
'"my new banner"'
FROM
your_meta_table
GROUP BY
post_id
HAVING
MAX(CASE WHEN meta_key = 'banner' THEN 1 ELSE 0 END) = 0
AND
MAX(CASE WHEN meta_key = 'page-type' AND meta_value = 'city' THEN 1 ELSE 0 END) = 1
或者,最好...
INSERT INTO
post (
post_id,
meta_key,
meta_value
)
SELECT
post_id,
'banner',
'"my new banner"'
FROM
your_posts_table
WHERE
NOT EXISTS (
SELECT *
FROM your_meta_table
WHERE post_id = your_posts_table.post_id
AND meta_key = 'banner'
)
AND EXISTS (
SELECT *
FROM your_meta_table
WHERE post_id = your_posts_table.post_id
AND meta_key = 'page-type'
AND meta_value = 'city'
)
在 MySQL 8.3 中,您可以:
meta_key = 'page_type'
和meta_value = 'city'
的所有“ post_id ”值,EXCEPT
操作減去所有帶有橫幅的 ID。INSERT INTO tab(post_id, meta_key, meta_value)
SELECT post_id,
'banner' AS meta_key,
'new_banner' AS meta_value
FROM (SELECT DISTINCT post_id FROM tab WHERE meta_key = 'page-type' AND meta_value = 'city'
EXCEPT
SELECT DISTINCT post_id FROM tab WHERE meta_key = 'banner') missing_ids;
您應該執行 Select into a temp-table 以實現此目的。
首先,我們選擇符合您條件的所有行:
SELECT (post_id) FROM [table] where meta_key = 'page-type' and meta_value='city' and
post_id not in (SELECT post_id FROM [table] WHERE meta_key='page-type' and meta_value='banner')
此選擇為您提供了一個不存在橫幅條目的 post_id 列表
現在您可以使用找到的 post_ids 將您需要的數據插入到您的表中:
INSERT INTO [table] (id, post_id, meta_key, meta_value)
SELECT id, post_id, meta_key, meta_value FROM (
SELECT null AS 'id', post_id, 'page-type', 'banner'
FROM [table]
WHERE meta_key = 'page-type'
AND meta_value='city'
AND post_id not in (
SELECT post_id FROM [table]
WHERE meta_key='page-type' AND meta_value='banner'
)
) as TEMP
你可以這樣做:
還要考慮如果橫幅存在則創建頁面類型的情況
INSERT into _metas (post_id, meta_key, meta_value)
select post_id, if(meta_key = 'page-type', 'banner', 'page-type'), if(meta_key = 'page-type', 'my banner', 'my city')
from your_meta_table
group by post_id
having count(*) = 1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.