表:产品: 属性:pid,名称
表名:item_product
属性:Itemid,@ pid,长度,价格,颜色。 pid是产品
的外键Itemid pid length price colour
1 1 3 5 blue
2 1 4 10 red
3 2 3 5 blue
4 2 6 20 green
5 3 4 4 g
6 4 3 3 r
7 1 3 4 e
8 1 4 6 r
9 2 6 100 light_blue
pid重复考虑了数据库,但上面的表格是一个小概念 我想从与产品ID相关的长度和颜色
中选择所有内容我有这个查询,但重复了
SELECT length,
price FROM item_product WHERE pid=:id
如果我运行上面的查询并将pid更改为1.它只会显示pid 1的所有内容但我只希望它显示它与name
中的产品product table
相关
答案 0 :(得分:0)
您可以使用INNER JOIN
之类的:
例如,我的产品名为Mouse
,Keyboard
,Monitor
,Tablet
和Hard Drive
。
在Item_Product
表格中,我只有鼠标,键盘,显示器和平板电脑的项目,但Hard Drive
没有。因此,当我INNER JOIN
时,两个表Hard Drive将被排除,因为它不在Item_Product
表中,但它位于Product
表中。
SELECT Itemid, B.name, length, price, colour
FROM item_product A
INNER JOIN product B
ON A.pid = B.pid
检查我的sqlfiddle
Demo
如果您只想查看特定产品,那么您可以使用productid(pid)或产品名称,如:
SELECT Itemid, B.name, length, price, colour
FROM item_product A
INNER JOIN product B
ON A.pid = B.pid
WHERE B.name = 'Mouse'
示例here
如果您想了解JOIN
的更多内容,请查看此link,它会向您显示JOIN
在sql中的工作方式的直观表示。
答案 1 :(得分:0)
您可以使用以下内容。我在表产品中使用了内部联接,并在名称上添加了 where 子句。< / p>
SELECT pt.name, length, price FROM item_product as pr inner join product as pt on pt.pid = pr.pid WHERE pr.pid = 1 and pt.name = 'name'
在where子句中,您需要按产品名称进行过滤。所以改变[名称],改变你的目标。
如果您只想按名称过滤,请执行与上述相同的查询,但仅对名称执行 where 子句。
SELECT pt.name, length, price FROM item_product as pr inner join product as pt on pt.pid = pr.pid WHERE pt.name = 'name'
如果这就是您的目的,请告诉我。