以下查询有效。我想替换字面值" 2"在列号为P0.TLKP_Parent
的最内层查询中。当我这样做时,我得到一个语法错误:
错误代码: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);
答案 0 :(得分:1)
问题是P0
无法识别表SELECT
,因为它不属于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 :(得分: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';