I have the following table structure:
CREATE TABLE a (
a_id int(10) unsigned NOT NULL AUTO_INCREMENT,
);
CREATE TABLE b {
b_id int(10) unsigned NOT NULL AUTO_INCREMENT,
};
CREATE TABLE cross (
a_id int(10) unsigned NOT NULL,
b_id int(10) unsigned NOT NULL,
PRIMARY KEY (a_id),
KEY (b_id),
CONSTRAINT FOREIGN KEY (a_id) REFERENCES a (a_id),
CONSTRAINT FOREIGN KEY (b_id) REFERENCES b (b_id)
);
CREATE TABLE prices (
a_id int(10) unsigned NOT NULL,
price int(10) NOT NULL,
PRIMARY KEY (a_id),
CONSTRAINT FOREIGN KEY (a_id) REFERENCES a (a_id)
);
I would like to retrieve every b_id value for which there are inconsistent prices. A b.id value ‘B’ has an inconsistent price if the following conditions both hold:
- There exist two a_id values (say, ‘A1’ and ‘A2’) such that table
crosscontains both (‘A1’, ‘B’) and (‘A2’, ‘B’). (For any b_id value, there may be zero or more rows incross.) - Either ‘A1’ and ‘A2’ correspond to rows of
pricesthat have different values ofprice, or else exactly one of ‘A1’ and ‘A2’ corresponds to an entry inprices.
Because of restrictions by the hosting provider, I cannot use stored procedures with this data base. I haven’t figured out a sensible way to do this with SQL queries. So far, I’ve resorted to retrieving all relevant data and scanning for inconsistencies in Perl. That’s a lot of data retrieval. Is there a better way? (I’m using InnoDB, if it makes a difference.)
1 Answer