这个查询对我来说很复杂。第一种情况有效。我试图添加第二个案例;但是,无法让它发挥作用。一个案例在陈述时是否需要超过1个?我完全错了第二种情况吗?
我需要第二种情况的唯一原因是因为当table1.data_lock = 0
时,没有table2.id
等于0.我只希望它包含table2 IF table1.data_lock != 0
可能有更好的方法。
SELECT table1.id, table1.draft_sectionid, table1.page_columnid, table1.sortid,
(case
when table1.data_lock = 0 then table1.data
when table1.data_lock != 0 then table2.data
end) as data,
table1.style
FROM table1
(case
when table1.data_lock != 0 then JOIN table2 ON table1.data_lock=table2.id
end)
WHERE table1.draft_sectionid = " . $section['id'] . " ORDER BY table1.sortid ASC LIMIT " . $section['columns']) or die ('Unable to execute query. '. mysqli_error($connection));
答案 0 :(得分:1)
无法使用case-when来定义select的结构。
但是,在这种情况下,您可以使用subselect生成值:
SELECT table1.id, table1.draft_sectionid, table1.page_columnid, table1.sortid,
(case
when table1.data_lock = 0 then table1.data
when table1.data_lock != 0 then (select table2.data from table2 where table2.id = table1.data_lock)
end) as data,
table1.style
FROM table1
WHERE ...
答案 1 :(得分:1)
不,您可以尝试使用CASE
表达式来更改连接表。您可以使用外部联接
SELECT table1.id, table1.draft_sectionid, table1.page_columnid, table1.sortid,
(case when table1.data_lock = 0 then table1.data
else table2.data end) as data,
table1.style
FROM table1
LEFT JOIN table2 ON table1.data_lock != 0 AND table1.data_lock = table2.id
WHERE table2.id IS NOT NULL
AND table1.draft_sectionid = " . $section['id'] . "
ORDER BY table1.sortid ASC
LIMIT " 1;
答案 2 :(得分:0)
SELECT table1.id, table1.draft_sectionid, table1.page_columnid, table1.sortid,
(case
when table1.data_lock = 0 then table1.data
when table1.data_lock != 0 then table2.data
end) as data,
table1.style
FROM table1 JOIN table2 ON table1.data_lock=table2.id and table1.data_lock != 0
WHERE table1.draft_sectionid = " . $section['id'] . " ORDER BY table1.sortid ASC LIMIT " . $section['columns']) or die ('Unable to execute query. '. mysqli_error($connection));
mysqli
使用此查询。