A little background so you understand what I'm trying to do. I am making a page that takes two user input products and checks to see if they are compatible with one another. This is an n+1*n mySQL table because there are n products.
The table looks like开发者_Go百科
name a b c d e
a
b
c
d
e
I already know that every product is compatible with itself, so to save time, is there a query that will automatically fill the table out so that I can get
name a b c d e
a 1
b 1
c 1
d 1
e 1
Thanks
I forgot to mention, each product can be compatible with an several other products. The diagonal I'm putting in is just a starting point.
Not a direct answer to your question but I felt I had to mention it...
If possible you should consider changing your design to the following:
compatible_products product1 product2 a b a c b d etc...
If you insert rows for both (a, b) and (b, a) then your query is simple:
SELECT 1
FROM compatible_products
WHERE product1 = 'a' AND product2 = 'b'
Also, when you add new products you won't have to change your database schema.
Not an answer to your question, but this sounds like a design mistake.
This way, you would have to add a new column to your table for every new product that comes up.
I think the much better way would be normalizing the table into one products
and one compatibility
table.
Each compatibility relationship between a product and another would be one record.
The compatibility
table could look like this:
id product1 product2
0 12 34
1 33 32
2 54 1
3 65 328
Queries would become extremely easy. To find out a relationship, you would have to do a simple
SELECT id FROM compatibility WHERE (product1 = 18 and product2 = 23)
OR (product1 = 23 and product2 = 18)
精彩评论