MySQL express constraint as calculated column?
Columns: id INT, provice_id INT, is_province BIT
Foreign key: province_id references City (id)
I'd like to express the concept: when id == province_id
then is_province == 1
. How can i express this? Maybe with a calculated colu开发者_运维技巧mn or another constraint?
EDIT: ok so many comments, i will explain why there is is_province attribute. I know it's redundant, but the table will hold about 8000 entries so the wast of space is not important at all. I'm adding is_province because (using DOctrine2) i can query for provinces more easly:
$provinces->findByIsProvince(true)
And yes, i'm mixing provinces and cities in one table, because a province is actually a city and share all attributes of it.
So my question is still, how can enforce constraint that if (id == province_id) then is_province == 1
?
The information would be redundant if you stored it in the table additionally. It's a perfect candidate for a view.
CREATE TABLE my_tbl(id INT, provice_id INT);
CREATE VIEW my_view AS
SELECT id, provice_id, (id = province_id) AS is_province
FROM my_tbl;
That gives you TRUE
/ FALSE
for is_province
. If you want 1 / 0, then substitute:
CASE WHEN id = province_id THEN 1 ELSE 0 END AS is_province
More on how to create views in the manual.
may be your dont need is_province
your could just select provinces by addWHERE id = province_id
精彩评论