MySQL比较结果0和1

时间:2022-05-31 22:50:38

I need to get a result from two selects, and compare them.

我需要从两个选择中获得结果,并比较它们。

Their values should return 0 or 1, if one of them is 1, then it's 1. 1 will always have a greater priority than 0.

它们的值应返回0或1,如果其中一个为1,则它为1. 1将始终具有比0更高的优先级。

This:

这个:

  1. 1st returns 0, 2nd returns 1, then it's 1.
  2. 1st返回0,2nd返回1,然后返回1。
  3. 1st returns 1, 2nd returns 0, then it's 1.
  4. 1st返回1,2nd返回0,然后返回1。
  5. Both returns 1, obviously it's 1.
  6. 两者都返回1,显然它是1。
  7. Both returning 0, finally it's 0.
  8. 两者都返回0,最后是0。

2 个解决方案

#1


1  

Just wrap it in another SELECT and use OR. MySQL already treats 1 as true and 0 as false.

只需将其包装在另一个SELECT中并使用OR即可。 MySQL已将1视为true,将0视为false。

Try these:

试试这些:

SELECT (SELECT 1) OR (SELECT 0) AS result
// Returns 1

SELECT (SELECT 0) OR (SELECT 0) AS result
// Returns 0

#2


2  

Wrap the two expressions in GREATEST() to return the greatest value, which would be 1 if either is 1 and 0 if neither is:

在GREATEST()中包装两个表达式以返回最大值,如果其中一个为1则为1,如果两者为0则为0:

SELECT GREATEST(col1, col2) AS result

If it is across two subselects:

如果它跨越两个子选择:

SELECT GREATEST(
  (SELECT col1 FROM tbl1 WHERE val='something'),
  (SELECT col2 FROM tbl2 WHERE val='something else')
) AS result

#1


1  

Just wrap it in another SELECT and use OR. MySQL already treats 1 as true and 0 as false.

只需将其包装在另一个SELECT中并使用OR即可。 MySQL已将1视为true,将0视为false。

Try these:

试试这些:

SELECT (SELECT 1) OR (SELECT 0) AS result
// Returns 1

SELECT (SELECT 0) OR (SELECT 0) AS result
// Returns 0

#2


2  

Wrap the two expressions in GREATEST() to return the greatest value, which would be 1 if either is 1 and 0 if neither is:

在GREATEST()中包装两个表达式以返回最大值,如果其中一个为1则为1,如果两者为0则为0:

SELECT GREATEST(col1, col2) AS result

If it is across two subselects:

如果它跨越两个子选择:

SELECT GREATEST(
  (SELECT col1 FROM tbl1 WHERE val='something'),
  (SELECT col2 FROM tbl2 WHERE val='something else')
) AS result