2014-01-17 123 views
0

我甚至不確定這裏是否有正確的術語。 MySQL新手,或多或少。替代GROUP_CONCAT?多個連接到同一個表,不同的列

給出定義的情侶表如下:

CREATE TABLE users 
(user_id int(11) NOT NULL auto_increment 
, name VARCHAR(255) 
, pri_location_id mediumint(8) 
, sec_location_id mediumint(8) 
, PRIMARY KEY (user_id) 
); 

CREATE TABLE locations 
(location_id mediumint(8) NOT NULL AUTO_INCREMENT 
, name varchar(255) 
, PRIMARY KEY (location_id) 
) 

我試圖做一個查詢一氣呵成獲取用戶名和主要和次要的位置。

我能得到一個這樣的:

SELECT u.name AS user_name, l.name as primary_location FROM users u, locations l WHERE u.primary_location_id=l.location_id 

但我吸取了正確的語法一片空白使用在一個查詢來獲取兩者。

+0

你只想要位置名稱? –

+0

兩個位置名稱。 – Flyingdiver

+0

只需加入表格兩次 - 每次使用不同的別名 – Strawberry

回答

2
SELECT u.name AS user_name, l1.name as primary_location , l2.name as secondary_location 
FROM users u 
JOIN locations l1 ON(u.pri_location_id=l1.location_id) 
JOIN locations l2 ON(u.sec_location_id = l2.location_id); 
+1

謝謝。我想我現在有工作。 – Flyingdiver

-1
首先

,我會認真考慮改變你的數據庫架構,如果允許添加可被用於正確地描述這種多對多的關係users_locations表。

此表可能看起來像:

user_id location_id location_type 
1   1    primary 
1   2    secondary 
2   1    secondary 
2   2    primary 

等等。

您可能需要跨所有三列的複合主鍵。而location_type可能最好是枚舉數據類型。然後

您的查詢會像

SELECT 
    u.name AS user_name 
    l.name AS location_name 
    ul.location_type AS location_type 
FROM users AS u 
INNER JOIN user_location AS ul /* possibly use left join here if user can exist without a location */ 
    ON u.user_id = ul.user_id 
INNER JOIN locations AS l 
    ON ul.location_id = l.location_id 
ORDER BY ul.location_type ASC 

這將返回最多每位使用者有兩個記錄(首先列出原發性和繼發性,原發性單獨記錄)

如果你需要這個壓縮成一個記錄你可以做到這一點:

SELECT 
    u.name AS user_name 
    COALESCE(CASE WHEN ul.location_type = 'primary' THEN l.name ELSE NULL END CASE) AS primary_location, 
    COALESCE(CASE WHEN ul.location_type = 'secondary' THEN l.name ELSE NULL END CASE) AS secondary_location 
FROM users AS u 
INNER JOIN user_location AS ul /* possibly use left join here if user can exist without a location */ 
    ON u.user_id = ul.user_id 
INNER JOIN locations AS l 
    ON ul.location_id = l.location_id 
GROUP BY `user_name` 

如果你被困在當前模式,那麼@Jlil解決方案應該爲你工作。

相關問題