2017-03-02 89 views
0

下面的查詢有效。我想用列名P0.TLKP_Parent替換最內層查詢中的字面值「2」。當我這樣做,我得到一個語法錯誤:執行關聯的正確方法

錯誤代碼:1054未知列「P0.TLKP_Parent_PK」在「where子句」

SELECT p0.*,x.nm 
From t_child P0 
, 
(
    SELECT p1.nm 
    FROM mydb.tlkp_parent P1 
    where p1.lang_cd="FR" 
    AND 
    p1.CORE_VAL= 
    (
     select CORE_VAL 
     FROM mydb.tlkp_parent P2 WHERE 
     (p2.PK =2) '<== want the '2' to be replaced with P0.TLKP_Parent 
    ) 
) as x 
where P0.TLKP_Parent_PK=2 

如何解決這一問題? 有沒有更好的方法來寫這個查詢?

謝謝。 注:DDL:

DROP TABLE IF EXISTS t_child; 

CREATE TABLE t_child (
    Seq_id int(11) NOT NULL AUTO_INCREMENT, 
    SomeData varchar(45) DEFAULT NULL, 
    TLKP_Parent_PK int(11) NOT NULL, 
    PRIMARY KEY (Seq_id), 
    KEY fk_t_Child_TLKP_Parent_idx (TLKP_Parent_PK) 
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; 

DROP TABLE IF EXISTS tlkp_parent; 

CREATE TABLE tlkp_parent (
    PK int(11) NOT NULL, 
    Core_Val int(11) DEFAULT NULL, 
    Lang_Cd char(2) DEFAULT NULL, 
    nm varchar(45) DEFAULT NULL, 
    PRIMARY KEY (PK) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 

INSERT INTO tlkp_parent 
(PK, Core_Val, Lang_Cd, nm) VALUES 
(1,100,'EN', 'A in English'), 
(2,101,'EN', 'B in English'), 
(3,102,'EN', 'C in English'), 
(4,100,'FR', 'A in French'), 
(5,101,'FR', 'B in French'), 
(6,102,'FR', 'C in French'); 

INSERT INTO `t_child` 
(Seq_id, `SomeData`, `TLKP_Parent_PK`) VALUES 
(1, 'some data for Bed',2), 
(2, 'some data for Couch',2); 
+1

子表中沒有數據!?!? – Strawberry

+0

@Strawberry,我編輯了這個問題來添加一些數據。謝謝。 – NoChance

+1

您可以將3個值插入2列。這是如何運作的? – Strawberry

回答

1

我不能真的看到你的查詢和這個之間的區別:

SELECT c.* 
    , y.nm 
    FROM t_child c 
    JOIN tlkp_parent x 
    ON x.pk = c.tlkp_parent_pk 
    JOIN tlkp_parent y 
    ON y.core_val = x.core_val 
WHERE y.lang_cd = 'FR'; 
+0

非常感謝您花時間提供簡潔易讀的解決方案。確實非常優雅! – NoChance

1

的問題是,該表P0SELECT無法識別,因爲它不是inner join的一部分,試試這個:

SELECT p0.*, (SELECT p1.nm 
    FROM mydb.tlkp_parent P1 
    where p1.lang_cd="FR" 
    AND 
    p1.CORE_VAL= 
    (
     select CORE_VAL 
     FROM mydb.tlkp_parent P2 WHERE 
     (p2.PK =P0.TLKP_Parent_PK) 
    )) as nm 
    FROM t_child P0 
where P0.TLKP_Parent_PK=2 
+1

非常棒,非常感謝! – NoChance

+0

@NoChance可能是非常出色和聰明的,可能還有進一步的改進空間。 – Strawberry

+0

@Strawberry,任何想法都會很棒。你是否建議我在新問題中要求優化? – NoChance

相關問題