【问题标题】:joining 2 tables one having multiple rows that matches to first table's row加入 2 个表,其中一个表具有与第一个表的行匹配的多行
【发布时间】:2018-03-25 01:23:18
【问题描述】:

我遇到了这样一种情况,我有 2 个表,一个有 id 作为 PK,另一个有,另一个有时间戳、状态和 id 作为 PK。当 table1 的 id 与表 2 的 id 匹配时,我想从 table1 中选择所有唯一行。

例如:

表1

-----id------------时间戳--------------状态- ------------col3------

.....111............2017-10-05 10:42:23........ .........

.....111.......2017-10-05 12:42:23.......X. .........

.....111......2017-10-05 18:42:23....... .........

.....222......2017-10-05 11:42:23....... .........

表2

-----id------------col2--------------col3- ------------col4------

.......111............CCCC............KKKY ..........

.....222............HSGHXF............OPUB.. ........

在这里,我想从 table1 中仅选择 2 个唯一行,一个具有 id 111,另一个具有 id 222。

【问题讨论】:

  • 注意:id 不是唯一的(在任一表中),因此它不能是主键。请改写您的问题...
  • 我做到了。 id是第二个表中的PK。
  • 我不确定这里发生了什么,但在我看来,表 1 中 ID 为 111 的所有三行都是唯一的。它们都有不同的状态和时间戳。您可能需要重新表述问题。
  • table1 中的所有表都应该是唯一的,这就是我将 id,ts,status 设置为 PK 的原因。但是,我想从表 2 中选择与表 1 具有相同 ID 的唯一行。意思是 1 行 111 id 和另一行 222 id
  • 但是 table1 中有 3 行 key = '111',所以您必须选择:您希望在结果集中出现哪一个

标签: sql postgresql join


【解决方案1】:

试试:

SELECT * FROM table1 AS tbl1 LEFT JOIN table2 AS tbl2 ON tbl1.ID = tbl2.ID

【讨论】:

  • 这将选择 id 为 111 的所有 3 行。我只想要 2 个唯一的行
  • 做不同的内连接
  • group by tbl1.ID 它对你有用吗?如果没有,请发送表格详细信息。
【解决方案2】:
    // I Have two unique rows match and display data in table...   

 <?php
                $con=mysql_connect('localhost','root','')or die("not connect".mysql_error());

                    $db=mysql_select_db('persons')or die("could Not connect".mysql_error());




        $res="select persond.personid,orders.OrderNumber,persond.firstname,persond.lastname from persond LEFT JOIN orders ON persond.personid=orders.PersonID" or die("could Not select".mysql_error()); 

        $query=mysql_query($res);

        echo "<table border='1'>";

                        echo "<th>id</th><th>first Name</th><th>lastname</th><th>ordernumber</th>";

                        while($row=mysql_fetch_array($query)){

        echo "<tr>";
                        //echo "<td><br/>".$row['id']."</td>";
                        echo "<td>".$row['personid']."</td>";
                        echo "<td>".$row['firstname']."</td>";
                        echo "<td>".$row['lastname']."</td>";
                        echo "<td>".$row['OrderNumber']."</td></tr>";
        }

        ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 2014-08-09
    • 2018-05-17
    • 2014-11-05
    • 2020-08-25
    相关资源
    最近更新 更多