I need to add a constraint to validate that number of rows referencing master table is lower than value in master row, e.g we have a table
master(master_id int pk, max_val int)
and slave(slave_id int pk, master_id fk ref master(master_id))
(so slave is de facto a colection of something), and I want that count(master_id)
in slave
is <= than max_val
for this master_id
. I have a constraint
constraint NO_MORE_PASS check ((select count(head_id) from parts p where
p.head_id = head_id) <= (select max_val from head where id = head_id));
(not sure if it is correct, however SQL Server tells that subqueries are not allowed (sql server 2017) so...).
I have also read Check Constraint - Subqueries are not allowed in this context, so the question: is there any other alternative (I would like to avoid using trigger)?.
I'am using this in spring app with spring data jpa (and hibernate) - may be useful, but would like to make it on db side rather than in the app. Nethertheless entity it is like:
@Entity
@Table(name = "route_parts")
data class RoutePart(
@Id
@Column(name = "route_part_id")
@GeneratedValue(strategy = GenerationType.AUTO)
var id: Long? = null,
//...
@Column(nullable = false)
var slots: Int? = null,
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "route_part_passengers",
joinColumns = [(JoinColumn(name = "route_part_id"))],
inverseJoinColumns = [(JoinColumn(name = "user_id"))]
)
var passengers: Set<ApplicationUser> = setOf()
)
and in that case ApplicationUser
is a slave (or better - another table will be created, and actually this will be that slave table) limited by slots
value.
So the question is...
How can I achieve limiting number of ApplicationUser
attached to each RoutePart