0

Ok, I have a problem that i've searched and searched for solutions to online and can't find any leads, here it is (oh, and i'm very new to this database stuff ;-)

Lets say I have thousands of retail stores and each one can carry 1 to 100 products, but there are 10,000 possible products available. I need each store owner to be able to see (and edit) the list of products in their store - this is straightforward and I can figure out the table structure for this - but what I also want to do is to be able to find the most common product combinations across stores, so for example I want to see something like:

120: pid34, pid234, pid876, pid120, pid100
118: pid45, pid54, pid657, pid763, pid237
115: pid23, pid546, pid657, pid543, pid23

Where the first number is the number of stores with those products (order of the products within the store doesn't matter), and the pid numbers are the product ids of the products (except remember there could be up to 100 products in each store).

So if I set up a table of:

ID, PID,    Store ID
1,  pid34,  10
2,  pid234, 10
3,  pid876, 10
4,  pid120, 10
5,  pid100, 10
6,  pid45,  45
... etc ...

I can keep track of my store inventories, but i've no idea how I can do my 'combinations' search, help!

4

3 回答 3

1

您应该能够使用数据库查询来解决这个问题的大部分,但是您仍然需要围绕此查询包装的另一种编程语言(例如 java 和 JDBC)。假设您使用的是某种 SQL 数据库。从您的结构来看,我认为您将需要使用 group by 子句。虽然我不知道你的数据库结构,因为你没有提到它,所以为了这个,我打算说你的表被称为“产品”

我们首先设计一个查询来获取每个产品的数量:

SELECT pid, COUNT(*) AS NUM FROM products p GROUP BY pid ORDER BY NUM DESC;

所以这个查询将返回如下内容:

pid,    NUM
pid34   120
pid29   120
pid20   20

所以,这越来越接近了,但仍然不是我们想要的。但是,现在通过将查询与编程语言结合使用,事情可以轻松完成。我在下面做了一些java代码作为例子。

// Assumes that database connection has already been made and is in the variable: conn1
Statement stmt1 = conn1.createStatement();
ResultSet rs1 = stmt1.executeQuery("SELECT pid, COUNT(*) AS NUM FROM products p GROUP BY pid ORDER BY NUM DESC");

int prevNum = -1;
while(rs1.next())
{
    int thisNum = rs1.getInt("NUM");
    if(thisNum != prevNum)
    {
        // this means it is a different number than the last result, start a new line
        system.out.print("\n" + thisNum + ": ");
        prevNum = thisNum;
    }
    system.out.print(rs1.getString("pid") + ", ");
}
stmt1.close();
conn1.close();

虽然我可能没有正确的逻辑,尤其是在格式化方面,但这应该能让你走上正确的道路,了解你需要如何去做。确实,这个问题需要结合使用查询和编程语言来解决。

查询可以解决一小部分问题,但是它们在解决这些问题方面做得非常好,而编程语言可以解决更广泛的问题。但是,在许多情况下,编程语言在解决相同问题方面的效率不如数据库,这就是为什么将两者多次结合可以更高效地解决复杂问题的原因。

于 2009-03-10T03:04:12.913 回答
0

This is categorically not a database problem. This is a problem which something like Prolog or ECLiPSe would be great for, or perhaps a constraint solver within some other language.

于 2009-03-10T02:03:57.300 回答
0
var1 = Select the unique store numbers

foreach var1
  select the products that apply to that store number.
/foreach

Justice is right though, this is not neccessarilly a database problem, but rather a more general programming problem.

于 2009-03-10T02:32:11.290 回答