【问题标题】:Mysql query to join tables and select only the rows that are not null and that have equal idsMysql查询连接表并仅选择不为空且具有相同ID的行
【发布时间】:2014-04-08 06:06:44
【问题描述】:

我有 10 张桌子。其中 1 个表有点像“集线器”。其他用于标识特定属性。 hub 表包含每个 id,而其他表只携带该表所需的 id。

我需要一个连接查询,它可以根据 id 将中心表中的所有行与任何子表中的所有行连接起来。

因此,例如,如果中心表中的一行的 id 为 9,而其中一个子表的 id 为 9,它应该加入它们。它不应该连接不存在的行并且不能包含为空的列。

我正在使用 Zend-Framework 来解决这个问题,但我很乐意收到有关如何在 zend-framework 或标准 php/sql 中执行此操作的建议。

这是我现在正在使用但不起作用的示例。此查询获取必要的信息,但也包括空行。除此之外,它还清空了我需要的子表行中的 id。

$select = $this->db->select()
     ->from("widgets")
     ->joinLeft("widget_login", "widgets.id = widget_login.id")
     ->joinLeft("widget_admin", "widgets.id = widget_admin.id")
     ->joinLeft("widget_text", "widgets.id = widget_text.id")
     ->joinLeft("widget_image", "widgets.id = widget_image.id")
     ->joinLeft("widget_facebook", "widgets.id = widget_facebook.id")
     ->joinLeft("widget_twitter", "widgets.id = widget_twitter.id")
     ->joinLeft("widget_google", "widgets.id = widget_google.id");

【问题讨论】:

    标签: php mysql sql zend-framework


    【解决方案1】:

    我认为您应该附加到您的查询中:

    ->where('(not(widgets_login is null)) and (not(widgets_admin is null)) and ... (The same here for all your tables);
    

    【讨论】:

    • 附加 where 语句可能是答案,但我不确定是否是这样。当我添加结果完全为空时,该语句的语法可能是错误的。
    • 您是否尝试运行自己编写的普通 SQL 查询(例如您尝试自动构建的查询)并查看它返回的内容?有时返回null 是正确的,只是因为我们正在查询的数据中存在另一个逻辑错误/错误:)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    相关资源
    最近更新 更多