PHP从没有特定关系的表中获取数据

时间:2018-02-13 22:35:41

标签: sql select inner-join

我有两张表(CONTROL& PAYMENT),如下所示:

          CONTROL                                       PAYMENT
+--------------------------+                   +------------------------+
|  CNUMBER    |    SERIAL  |                   |  NUMBER    |   STATUS  |
+--------------------------+                   +------------------------+
| C-200-1     |  SUDU-03   |                   |    200     |    PAID   |
| C-201-1     |  SUDU-03   |                   |    201     |    PAID   |
| C-202-1     |  SUDU-03   |                   |    202     | PROCESSING|
| C-203-1     |  SUDU-03   |                   |    203     |    PAID   |
| C-204-1     |  SUDU-03   |                   |    204     | PROCESSING|
| C-204-1     |  SUDU-03   |                   |    205     | PROCESSING|
+--------------------------+                   +------------------------+

我想显示一个这样的列表:

+--------------------------+
|  CNUMBER    |    STATUS  |
+--------------------------+
| C-200-1     |    PAID    |
| C-201-1     |    PAID    |
| C-202-1     | PROCESSING |
| C-203-1     |    PAID    |
| C-204-1     | PROCESSING |
| C-205-1     | PROCESSING |
+--------------------------+

所以,我需要从表格#34;控制"中获取数据(SELECT)。使用" serial" (在控制表中)像搜索条件一样找到"状态" (在付款表中)通过"号码" (在付款表中)使用%LIKE%(匹配"数字"和" cnumber")

我正在尝试,但我仍然无法弄明白! 我希望有人可以帮助我并给我任何想法。

编辑:

解决方案1:

从CONTROL c中选择c.CNUMBER,p.STATUS 在内部联系PAYMENT p on substr(c.CNUMBER,3,3)= p.NUMBER;

感谢@Syscall我解决了主要问题,但我只是有一点问题:

即使付款条目为空/空,我如何显示所有值? 如果进入'控制'存在,但在付款'不

类似的东西:

+--------------------------+
|  CNUMBER    |    STATUS  |
+--------------------------+
| C-200-1     |    PAID    |
| C-201-1     |            | <--empty
| C-202-1     | PROCESSING |
| C-203-1     |    PAID    |
| C-204-1     |            | <--empty
| C-205-1     | PROCESSING |
+--------------------------+

编辑2:

已解决,使用LEFT JOIN 再次感谢@Syscall。

解决方案:

从CONTROL c中选择c.CNUMBER,p.STATUS 左边加入PAYMENT p on substr(c.CNUMBER,3,3)= p.NUMBER在哪里col1 =&#39; $ var&#39;

1 个答案:

答案 0 :(得分:2)

您可以INNER JOIN使用SUBSTR

select c.CNUMBER,p.STATUS from CONTROL c
inner join PAYMENT p on substr(c.CNUMBER,3,3)=p.NUMBER;

输出:

+---------+------------+
| CNUMBER | STATUS     |
+---------+------------+
| C-200-1 | PAID       |
| C-201-1 | PAID       |
| C-202-1 | PROCESSING |
| C-203-1 | PAID       |
| C-204-1 | PROCESSING |
| C-204-1 | PROCESSING |
+---------+------------+