'Is it possible to set the standard value of a column to the value of another column?
I want the standard value of column B to be the value of Column A in the same row until it is changed through a user triggered UPDATE. Is that possible?
I'm using Mysql 8 and phpmyadmin, if that matters.
Solution 1:[1]
MySQL does not allow you to default a value using an expression with other columns.
One solution is an insert trigger on the table to set B to A. However, if A changes, this doesn't keep track -- unless you have an update trigger. But then you don't know when B is set manually or not. Oh, this is hard to keep track of.
You can do something else using a computed column -- assuming that you never want B to be set manually to NULL. This looks like:
create table t as (
. . . ,
a int not null,
_b int,
b int generated always as (coalesce(_b, a))
);
Then, in your code, you use b for querying. When you want to set the value, you would set the value of _b.
Of course, you could extend this to have a boolean flag on whether a or _b is used for b. However, using NULL to distinguish whether a value is set illustrates the idea and is simpler.
Solution 2:[2]
Please see the answer by John C in MySQL: set field default value to other column
I was able to alter a table setting the default value as the concatenation of two other columns in that table:
ALTER TABLE t_table MODIFY IDOne_IDTwo varchar(12) DEFAULT ( concat(IDOne,'-',IDTwo) );
Be sure to wrap parentheses around your expressions and leave the literals bare. MySQL documentation regarding allowing expressions as default values: Explicit Default Handling as of MySQL 8.0.13.
Solution 3:[3]
The cache tag bits are the bits within an address (from the perspective of the CPU) that are used as a tag based on the size and width of the cache.
Let us assume a very simple cache with 8 64 byte lines
the 6 least significant bits represent a location within a 64 byte line. The next 3 bits would be the tag, since we only have 8 lines
bits in address: ... xxxx xxxt ttxx xxxx
Addresses 0x86 and 0x10080 would have the same tag in this example
This is an oversimplified example, and there are many nuances to caches, so I would recommend reading some more in depth material on the topic, or read about an actual implementation (i.e. a CPU manual) to get a much better feel for how this works
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gordon Linoff |
| Solution 2 | SMich |
| Solution 3 | Sean K |
