gpt4 book ai didi

MySQL 选择。如果 WHERE 中的值不存在,则根据另一个(值)WHERE 进行 SELECT

转载 作者:行者123 更新时间:2023-11-29 00:07:37 26 4
gpt4 key购买 nike

我有这样的mysql表

CategoryForTest table

我有 2 个变量/值,例如 FLASHLCD

我想:如果 FLASH 不存在于列 name 中,则 SELECT ... WHEREname = '液晶屏'。如果FLASH存在,则不选择基于LCD

写了这样的查询

SELECT 

t1.name AS lev1, t1.url AS url1

FROM CategoryForTest AS t1
LEFT JOIN CategoryForTest AS t2 ON t2.parent = t1.category_id
LEFT JOIN CategoryForTest AS t3 ON t3.parent = t2.category_id
LEFT JOIN CategoryForTest AS t4 ON t4.parent = t3.category_id

WHERE exists (
SELECT name
from CategoryForTest
WHERE t4.name = 'FLASH'
)

UNION ALL

SELECT

t1.name AS lev1, t1.url AS url1

FROM CategoryForTest AS t1
LEFT JOIN CategoryForTest AS t2 ON t2.parent = t1.category_id
LEFT JOIN CategoryForTest AS t3 ON t3.parent = t2.category_id
LEFT JOIN CategoryForTest AS t4 ON t4.parent = t3.category_id

WHERE not exists (
SELECT name
from CategoryForTest
WHERE t4.name = 'FLASH'
)
AND t2.name = 'LCD'

但是我明白了

Array
(
[0] => Array
(
[lev1] => ELECTRONICS
[url1] => url-electronics
)

[1] => Array
(
[lev1] => TELEVISIONS
[url1] => url-televisions
)

)

期望只看到 [0] => Array

最佳答案

这可能对你有帮助。

(
SELECT

t1.name AS lev1, t1.url AS url1

FROM test AS t1
LEFT JOIN test AS t2 ON t2.parent = t1.categ_id
LEFT JOIN test AS t3 ON t3.parent = t2.categ_id
LEFT JOIN test AS t4 ON t4.parent = t3.categ_id

WHERE not exists (
SELECT

t1.name AS lev1, t1.url AS url1

FROM test AS t1
LEFT JOIN test AS t2 ON t2.parent = t1.categ_id
LEFT JOIN test AS t3 ON t3.parent = t2.categ_id
LEFT JOIN test AS t4 ON t4.parent = t3.categ_id

WHERE exists (
SELECT name
from test
WHERE t4.name = 'FLASH'
)
)
AND t2.name = 'LCD'
GROUP BY t1.categ_id
)
UNION ALL
(
SELECT

t1.name AS lev1, t1.url AS url1

FROM test AS t1
LEFT JOIN test AS t2 ON t2.parent = t1.categ_id
LEFT JOIN test AS t3 ON t3.parent = t2.categ_id
LEFT JOIN test AS t4 ON t4.parent = t3.categ_id

WHERE exists (
SELECT name
from test
WHERE t4.name = 'FLASH'
)
)

文件是 here

关于MySQL 选择。如果 WHERE 中的值不存在,则根据另一个(值)WHERE 进行 SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26773162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com