如何联接来自两个不同表的数据?

时间:2018-07-31 17:36:27

标签: sql join

表1:建筑物

    ProjectNO (FK)
    BuildingNO
    Floors
    location

表2:项目

    ProjectNO (PK)
    ProjectName
    CityName

我需要加入"project""Building",因为我需要使用Buildings键来ProjectBuilding中的公用ProjectNO。 / p>

谢谢

4 个答案:

答案 0 :(得分:0)

您似乎想要:

select b.*
from Building b
where exists (select 1 from Project p where p.ProjectNO = b.ProjectNO);

如果您想要ProjectName,CityName,则可以执行JOIN

select p.*, b.*
from Project p inner join
     Building b
     on p.ProjectNO = b.ProjectNO;

答案 1 :(得分:0)

您应该进行内部联接以从两个表中获取匹配记录,如下所示...

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QAction, QMenu, QTableWidget, QTableWidgetItem, QVBoxLayout
from PyQt5 import QtCore


class TestRightClickTableWidget(QWidget):

    def __init__(self):
        super().__init__()

        self.tableWidget = QTableWidget()
        self.tableWidget.setRowCount(4)
        self.tableWidget.setColumnCount(2)
        self.tableWidget.setItem(0, 0, QTableWidgetItem("Cell 1"))
        self.tableWidget.setItem(0, 1, QTableWidgetItem("Cell 2"))
        self.tableWidget.setItem(1, 0, QTableWidgetItem("Cell 3"))
        self.tableWidget.setItem(1, 1, QTableWidgetItem("Cell 4"))
        self.tableWidget.setItem(2, 0, QTableWidgetItem("Cell 5"))
        self.tableWidget.setItem(2, 1, QTableWidgetItem("Cell 6"))
        self.tableWidget.setItem(3, 0, QTableWidgetItem("Cell 7"))
        self.tableWidget.setItem(3, 1, QTableWidgetItem("Cell 8"))

        self.tableWidget.viewport().installEventFilter(self)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.tableWidget)
        self.setLayout(self.layout)

    def eventFilter(self, source, event):
        if(event.type() == QtCore.QEvent.MouseButtonPress and
           event.buttons() == QtCore.Qt.RightButton and
           source is self.tableWidget.viewport()):
            item = self.tableWidget.itemAt(event.pos())
            print('Global Pos:', event.globalPos())
            if item is not None:
                print('Table Item:', item.row(), item.column())
                menu = QMenu(self)
                menu.addAction(QAction('test'))
                menu.exec_(event.globalPos())
        return super(TestRightClickTableWidget, self).eventFilter(source, event)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = TestRightClickTableWidget()
    ex.show()
    sys.exit(app.exec_())

它将仅返回两个表中都存在ProjectNO的记录。

答案 2 :(得分:0)

您应该使用inner join关键字从两个表中获取匹配的记录。

如果要连接2个具有相同ProjectNO的表,

select * from Project p
     inner join
     Building b
     on p.ProjectNO = b.ProjectNO;

答案 3 :(得分:0)

仅使用inner join,因为INNER JOIN关键字会选择两个表中具有匹配值的记录。

  select p.*, b.ProjectName
    from Project p inner join
         Building b
         on p.ProjectNO = b.ProjectNO;