我有三张桌子。
组件:
id | name | storage | bilance |
| | | |
商店
id | name | price | componentId |
| | | |
和订单
id | item | amount | ... |
组件表包含产品。 商店桌上有售卖该产品的商店
所以例如
component( 1 , "wheel" , 15 , 15 );
和出售轮子的商店
Shops(1 , "wheelShopone" , 150 , 1);
Shops(2 , "Shoptwo" , 100 , 1 )
这基本上意味着你可以购买更多商店的轮子,例如1:n关系
订单包含要订购的内容,例如
orders(1 , "wheel" , 5 )
我想要做的是找到在某些商店出售的表格订单中的所有元素(例如组件)。
我尝试使用join例如
> Select components.name as comp_name , components.id as comp_id ,
> shops.name as shop_name , shops.id as shop_id , orders.item as item ,
> orders.amount as order_amount from components join shops join orders
> WHERE shop_name = some name
我期望它做的是跟随,imageine表
components shops
id | name | storage | bilance | id | name | price | componentId|
1 | wheel | 15 | 15 | 1 | One | 15 | 1
2 | mouse | 1 | 1 | 2 | two | 5 | 1
3 | three| 5 | 2
使用
加入这两个表> Select components.name as comp_name , components.id as comp_id ,
> shops.name as shop_name , shops.id as shop_id FROM Components join Shops
应该导致
comp_name | comp_id | shop_name | shop_id
wheel | 1 | one | 1
wheel | 1 | two | 2
mouse | 2 | three | 3
然后最终加入订单,例如
id | item | amount | ...
1 | wheel | 5 | ...
使用我之前提到的命令
> Select components.name as comp_name , components.id as comp_id ,
> shops.name as shop_name , shops.id as shop_id , orders.item as order_item , order.amount as order_amount FROM Components join Shops
> join Orders on components.name = orders.item
应该导致
comp_name | comp_id | shop_name | shop_id | item | amount
wheel | 1 | one | 1 | wheel| 5
wheel | 1 | two | 2 | wheel| 5
但是使用这个命令,它只是抛出随机表,它加入了看起来像crossjoin的东西,因为我得到了数百行数据。
我对连接的理解是否正确?如果没有我错在哪里,我怎么能做这个工作?谢谢你的帮助!
答案 0 :(得分:0)
你可能想要这样的东西:
SELECT components.name as comp_name,
components.id as comp_id,
shops.name as shop_name,
shops.id as shop_id,
orders.item as item,
orders.amount as order_amount
FROM shops JOIN components ON shops.componentId=components.id
JOIN orders ON components.id=orders.item
WHERE shop_name = some name
你缺少的主要是连接条件。通常,在进行连接时,必须指定一个条件,该条件将用于匹配两个表中的正确行。例如,条件shops.componentId=components.id
表示来自shops
的行与来自components
的行匹配,其中componentId
中的id
与组件的import sys
from PyQt5.QtWidgets import QHBoxLayout, QAction, QApplication, QMainWindow
class menudemo(QMainWindow):
def __init__(self, parent = None):
super(menudemo, self).__init__(parent)
bar = self.menuBar()
file = bar.addMenu("File")
file.addAction("New")
save = QAction("Save",self)
save.setShortcut("Ctrl+S")
file.addAction(save)
edit = file.addMenu("Edit")
edit.addAction("copy")
edit.addAction("paste")
quit = QAction("Quit",self)
file.addAction(quit)
file.triggered[QAction].connect(self.processtrigger)
self.setWindowTitle("menu demo")
def processtrigger(self, q):
print(q.text()+" is triggered")
def main():
app = QApplication(sys.argv)
ex = menudemo()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
相同。
答案 1 :(得分:0)
如果要进行连接,则必须告诉数据库两个表中的哪些行匹配:
SELECT ...
FROM Components
JOIN Shops ON Components.id = Shops.componentId;
即使您声明了外键约束,也不会自动推断出这种关系。
如果没有连接条件,您确实会得到交叉连接。