在两个表格中选择数据

时间:2015-12-14 06:56:30

标签: mysql sql mysqli

表1:

+-----------+----------+------------+
| FirstName | LastName | Qty        |
+-----------+----------+------------+
| Tia       | Carrera  |  5         |
| Nikki     | Taylor   |  8         |
+-----------+----------+------------+

表2:

+-----------+----------+------------+
| FirstName | LastName | Qty        |
+-----------+----------+------------+
| Tia       | Carrera  | 5          |
| Nikki     | Taylor   | 8          |
| Yamila    | Diaz     | 30         |
+-----------+----------+------------+

中行的示例输出
module.run(function($http) {
  $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
});

2 个答案:

答案 0 :(得分:3)

您应该使用与FirstName和LastName不同的列创建新列并定义PK和FK。但是使用当前结构,您可以使用LEFT JOINCOALESCE

SELECT t1.FirstName, t1.LastName, COALESCE(t2.Qty, t1.Qty) AS Qty
FROM table1 t1
LEFT JOIN table2 t2
  ON t1.FirstName = t2.FirstName
 AND t1.LastName = t2.LastName;

SqlFiddleDemo

输出:

╔════════════╦═══════════╦═════╗
║ FirstName  ║ LastName  ║ Qty ║
╠════════════╬═══════════╬═════╣
║ Nikki      ║ Taylor    ║   8 ║
║ Tia        ║ Carrera   ║   5 ║
║ Yamila     ║ Diaz      ║  30 ║
╚════════════╩═══════════╩═════╝

答案 1 :(得分:0)

可能会有所帮助

SELECT * FROM Table2
UNION ALL
SELECT * FROM Table1
    WHERE FirstName NOT IN(SELECT FirstName FROM Table2) AND 
          LastName  NOT IN(SELECT LastName FROM Table2)