如何在MySQL中选择具有匹配字段的行?

时间:2017-12-27 10:40:59

标签: mysql

我有2个表,一个有价格覆盖,一个有分钟覆盖,每个用户和产品。如何选择它们以便我有每个用户和产品的记录?

Table 2: All overrides
+--------+-----------+-------------+---------------+
| userID | productID | overrideMin | overridePrice |
+--------+-----------+-------------+---------------+
| 4      | 13        | null        | 99.99         |
| 4      | 18        | 23          | null          |
| 4      | 53        | null        | 99.99         |
| 4      | 55        | 4           | 99.99         |
| 50     | 55        | 2           | null          |
+--------+-----------+-------------+---------------+

我希望它生成的表格:

userID

我尝试过GROUP BY productIDproductID,但由于表1中可能存在表2中不存在的产品ID,因此根据{{1我分组。

3 个答案:

答案 0 :(得分:4)

使用UNION

SELECT userID, productID, 
  MAX(overrideMin) AS overrideMin, 
  MAX(overridePrice) AS overridePrice
FROM
(
    SELECT userID, productID, null AS overrideMin, overridePrice
    FROM OverridePrices
    UNION
    SELECT userID, productID, overrideMin, null AS overridePrice
    FROM OverrideMinutes
) AS t
GROUP BY userID, productID;

这将为您提供您正在寻找的exact results

| userID | productID | overrideMin | overridePrice |
|--------|-----------|-------------|---------------|
|      4 |        13 |      (null) |         99.99 |
|      4 |        18 |          23 |        (null) |
|      4 |        53 |      (null) |         99.99 |
|      4 |        55 |           4 |         99.99 |
|     50 |        55 |           2 |        (null) |

答案 1 :(得分:1)

您必须使用IF声明:

SELECT
  t1.userID,
  t1.productID,
  if (t2.overrideMin IS NULL, NULL, t2.overrideMin) AS overrideMin,
  if (t1.overridePrice IS NULL, NULL, t1.overridePrice) AS overridePrice
FROM OverridePrices AS t1
LEFT JOIN OverrideMinutes AS t2 ON t1.userID = t2.userID AND t1.productID = t2.productID;

但是如果你可以在table1和table2中拥有不同的产品,你必须加入包含所有产品的表,例如:

SELECT
  t1.userID,
  t1.productID,
  if (t2.overrideMin IS NULL, NULL, t2.overrideMin) AS overrideMin,
  if (t1.overridePrice IS NULL, NULL, t1.overridePrice) AS overridePrice
FROM (
  SELECT userID, productID FROM OverridePrices
  UNION
  SELECT userID, productID FROM OverrideMinutes
) AS t0
LEFT JOIN OverridePrices AS t1 ON t0.userID = t1.userID AND t0.productID = t1.productID
LEFT JOIN OverrideMinutes AS t2 ON t0.userID = t2.userID AND t0.productID = t2.productID;

此外,现在您可以拥有GROUPHAVING

答案 2 :(得分:0)

SELECT table1.userID,table1.productID,table2.overrideMin,table1.overridePrice FROM table1 
LEFT JOIN table2 ON table1.userID=table2.userID AND table1.productID = table2.productID 
UNION SELECT table2.userID,table2.productID,table2.overrideMin,table1.overridePrice FROM table1 
RIGHT JOIN table2 ON table1.userID=table2.userID AND table1.productID = table2.productID 
ORDER BY userID, productID

这是OUTPUT

enter image description here