查詢時遇到一些麻煩。我試圖創建從表中選擇deposit_type_language_id = 3或如果行不存在1(作爲後備)與deposit_type_id分組。MySQL從備用組中選擇
+-----------------+--------------------------+-------------------+
| deposit_type_id | deposit_type_language_id | deposit_type_name |
+-----------------+--------------------------+-------------------+
| 1 | 1 | jewellery |
| 1 | 2 | bijuterii |
| 1 | 3 | šperky |
| 2 | 1 | equipment |
| 2 | 2 | tehnica |
+-----------------+--------------------------+-------------------+
我試圖用下面的查詢:
SELECT t1.* from deposit_type AS t1
INNER JOIN
(SELECT deposit_type_id, min(deposit_type_language_id) from
deposit_type group by deposit_type_id) AS t2
ON t1.deposit_type_id=t2.deposit_type_id group by deposit_type_id;
輸出是:
+-----------------+--------------------------+-------------------+
| deposit_type_id | deposit_type_language_id | deposit_type_name |
+-----------------+--------------------------+-------------------+
| 1 | 1 | jewellery |
| 2 | 1 | equipment |
+-----------------+--------------------------+-------------------+
但我試圖實現類似如下:
+-----------------+--------------------------+-------------------+
| deposit_type_id | deposit_type_language_id | deposit_type_name |
+-----------------+--------------------------+-------------------+
| 1 | 3 | šperky |
| 2 | 1 | equipment |
+-----------------+--------------------------+-------------------+
在哪裏我的錯?
表結構:
deposit_type | CREATE TABLE `deposit_type` (
`deposit_type_id` smallint(5) unsigned NOT NULL,
`deposit_type_language_id` smallint(5) unsigned NOT NULL,
`deposit_type_name` varchar(96) NOT NULL,
PRIMARY KEY (`deposit_type_id`,`deposit_type_language_id`),
KEY `deposit_type_language_id` (`deposit_type_language_id`),
CONSTRAINT `deposit_type_ibfk_1` FOREIGN KEY (`deposit_type_language_id`) REFERENCES `language` (`language_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
@Strawberrry,嗨,哥們你的答案似乎是正確的。我正在學習你的答案,謝謝! – vit
如果你想用兩個字解釋你的想法,請。 – vit
@vit如果存在有效的連接,則左[outer]連接將返回值,否則返回NULL。然後COALESCE簡單地忽略NULL值。 – Strawberry