MYSQL 中的 CASE 表达式可以实现吗?
我读到的有关使用 CASE 的所有内容都意味着只能更改它引用的列中各个字段的内容。有没有办法引用另一个表中的字段?
我想要的不是(只是使用互联网上的随机示例)
SELECT daysName,
CASE daysName
WHEN "Sunday" THEN "Holiday"
:
CASE table1.column1
WHEN table3.column1 = "Yes" THEN table1.column1 + 80
如果没有,我该怎么做?
这些表有主键和外键,因此我可以使用联接。
Everything I've read about using CASE implies that it's only possible to change the contents of the individual field within the column it references. Is there a way to reference a field within another table?
Instead of (just to use a random example from the internet)
SELECT daysName,
CASE daysName
WHEN "Sunday" THEN "Holiday"
I want something like:
CASE table1.column1
WHEN table3.column1 = "Yes" THEN table1.column1 + 80
If not, how do I do this?
These tables have primary and foreign keys so I am able to use joins.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来您可以将
case
表达式转换为或者,您可以使用
IF
:当然,无论哪种方式,您都需要加入
table3
,并且您可能希望为该值指定一个别名,因为它不再是严格意义上的数据库中的字段。 (MySQL 将返回整个表达式作为列名。)It looks like you could turn the
case
expression intoOr, you could use
IF
:You'll need to join
table3
either way, of course, and you might want to give that value an alias, since it's no longer strictly a field in the DB. (MySQL will return that whole expression as the column name.)这:
...如果尝试对 CASE 表达式使用这两个语法选项,则应返回语法错误。如果没有更多信息,它应该是:
..因为示例中没有任何内容表明您正在使用 table1.column1 进行评估。
接下来 - 要使用
table3.column
比较,您需要一个联接。这可以是 INNER 或 OUTER JOIN,可能是笛卡尔积(CROSS JOIN)...但是您没有提供有关表之间关系的信息。This:
...should return a syntax error for attempting to use both syntax options for a CASE expression. Without more information, it should be:
..because there's nothing in the example to say you're using the table1.column1 for evaluation.
Next - to use the
table3.column
comparison, you need a join. That can be an INNER or OUTER JOIN, possibly a cartesian product (CROSS JOIN)... but you haven't provided information about what the relationship between the tables is.