[英]MySQL query to select rows matching criteria and rows related to the matching rows
[英]How to select rows with matching fields in MySQL?
我有2個表,一個有價格覆蓋,一個有分鍾覆蓋,每個用戶和產品。 如何選擇它們以便我有每個用戶和產品的記錄?
Table 1: Override Prices
+--------+-----------+---------------+
| userID | productID | overridePrice |
+--------+-----------+---------------+
| 4 | 53 | 99.99 |
| 4 | 13 | 99.99 |
| 4 | 55 | 99.99 |
+--------+-----------+---------------+
Table 2: Override Minutes
+--------+-----------+---------------+
| userID | productID | overrideMin |
+--------+-----------+---------------+
| 4 | 18 | 23 |
| 4 | 55 | 4 |
| 50 | 55 | 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 |
+--------+-----------+-------------+---------------+
我已經嘗試GROUP BY userID
, productID
,而是因為在表1中不表2中存在可能存在的產品ID,我得到這取決於不同的結果productID
通過I組。
使用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;
這將為您提供您正在尋找的確切結果 :
| 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) |
你必須使用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;
此外,現在您可以擁有GROUP
, HAVING
等。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.